PHP Basic Syntax | Variables, Array, Data types, Strings
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
:
// PHP code goes here
The default file extension for PHP files is “.php”.
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script
that uses a built-in PHP function “echo” to output the text “Hello World!” on a web page:
‘Syntax’ is the structure of statements in a computer language. The syntax of PHP is very easy to understand compared to some other programming languages.
You may like
- PHP Array: Indexed,Associative, Multidimensional
- Create Modern Website Using HTML CSS
- How to Convert String to Array in PHP
- Data types in php | php data types in hindi
Example
PHP
echo "Hello, world!";
Output:
Hello, world!
SGML or Short HTML Tags: These are the shortest option to initialize a PHP code. The script starts with <?and ends with ?>
. This will only work by setting the short_open_tag setting in the php.ini file to ‘on’.
Example:
PHP
echo "Hello, world!";
Output:
Hello, world!
HTML Script Tags: These are implemented using script tags. This syntax is removed in PHP 7.0.0. So its no more used.
Example:
PHP
<script language="php">
echo "hello world!";
</script>
Output:
hello world!
ASP Style Tags:To use this we need to set the configuration of the php.ini file. These are used by Active Server Pages to describe code blocks. These tags start with <% and end with %>.
Example:
PHP
<%
# Can only be written if setting is turned on
# to allow %
echo "hello world";
%>
Output:
hello world
Constants:
Constants can be defined using the const keyword or define() function.
There is some difference between constants and variables.
- Constants do not have $ in front of them like variables have.
- Constants can be accessed from anywhere without regard to variable scoping rules.
PHP Case Sensitivity
Look at the example below; only the first statement will display the value of the $color variable! This is because $color, $COLOR, and $coLOR are treated as three different variables:
Example:
<!DOCTYPE html>
<html>
<body>
// php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
</body>
</html>
You may like