php variables, functions, if, for, while, switch syntax - quick through

The PHP script is executed on the server and the HTML result is sent to the browser. It can normally have HTML and PHP tags. PHP or Hypertext Preprocessor is a widely used open-source general-purpose scripting language and can be embedded with HTML. PHP files are saved with the .php extension. PHP scripts can be written anywhere in the document within PHP tags along with normal HTML.

Variables

In PHP, a variable is declared using a $ sign followed by the variable name.PHP is a loosely typed language, so we do not need to declare the data types of the variables.
Syntax of declaring a variable in PHP
$variablename=value; 
variable variable
A variable variable takes the value of a variable and treats that as the name of a variable.This would be useful in future when using variables inside loops
Syntax of declaring a variable variable in PHP
$$variablename=value; 

Functions

PHP functions are only defined once and we can invoked many times.This helps to reduce code complexity.
Syntax of declaring function in PHP

function functionname(){
//execution code
}  
example:

//define function displayWord
function displayWord($word){
echo $word;
}  

//call method
$wordToDisplay=‘Hello World‘ ;
displayWord($wordToDisplay);

If Statement

if statement used in code if one condition is true.
Syntax of if

if (condition) {
  execute code;
} 
example:

if ($x>10) {
  $y=true;
} 
you can use if else in the same way with additional code segment

if (condition) {
  execute code;
} 
else{
  execute another code;
}

for Statement

The for loop used when we know how many times the script should execute.
Syntax of for

for ($from; $condition; $increment) {
    execute code;
}
example:

for ($x=0; $x<10; $x=$x+1) {
    $y=$x;
    echo $y;
}

switch Statement

Switch use to select one of many values of code to be read and execute.
Syntax of switch

switch (n) {
  case 01:
    execute code only if case = 01;
    break;
  case 02:
    execute code only if case = 02;
    break;
    ...
  default:
    execute code only if none above;
}
example:

$x=100;
switch ($x) {
  case 10:
    $y=10;
    break;
  case 20:
    $z=20;
    break;
    ...
  default:
    $a=0;
}

Rasika Preethiraj

A technophile at icrony since 2012, In a quest to programmatic automations for scaled organisations through the use of python, php, autoit and machine learning


Comments


Post a Comment



Trending

Latest Posts

Tags

Newsletter

Subscribe to our newsletter for good news, sent out every month.