Home‎ > ‎PHP‎ > ‎

Variables

PHP is interpreted and similar to most high level languages that follow the C style syntax.. and OOP similar to Java and C++

Variables in PHP


PHP tag start with
 
<?php

// Code Statement

?>

Varible declare using $(dollor) sign. No need to assign datatype.

to dispaly variable PHP have number of command to display.

printf() , sprintf() , print() , echo()

PHP also support C Programming style printf.

// Example using c language.
int num = 100 ;
printf("%d" , num) ;

// Example using PHP language

$num = 100 ;
printf("%d" , $num) ;

Syntax : printf(format , argument1, argument2) ;

Format :
  • %b - Binary number
  • %c - The character according to the ASCII value
  • %d - Signed decimal number
  • %u - Unsigned decimal number
  • %f - Floating-point number (local settings aware)
  • %F - Floating-point number (not local settings aware)
  • %o - Octal number
  • %s - String
  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)printf("%d" , $num) ;

or can use echo or print without define format

Example : echo $num

String display using quotes either single (') or double (")

$name = 'Kamal' ; // Varibale declare

Check variable datatype
  • is_string(variable) - to check variable is string or not.
  • is_bool(variable) - to check variable is boolean or not
  • is_finit(variable) - to check variable value is finite or not
  • is_integer(variable) - to check variable value is integer or not
  • and some others.
Example :

echo is_string($name) ; // Display 1 if match.

or

return the exact data-type - using gettype() function that return datatype assign to variable

Syntax : gettype(variable) ;

Example:
echo gettype($name) ;

Output:
string

typecasting. it will return variable value if typecasting match, else return 0

echo (string)($name) ;

Concatenation - by using . (dot) Operator

echo "Name is " . $name . "from SKJ" ;

or

// this will also work in quotes.. but not optimize for performance.
echo "Name is $name from SKJ" ;


PHP work with HTML

Example : create a HTML DIV in PHP and assign $name variable value in DIV
echo "<div id='1'>$name</div>" ;

or

use this outside PHP tags.. pure HTML code work outside PHP tags.
<div id="1">
    <?php echo $name ?>
</div>
Comments