How to use variable and statements in php?

0 Comments

PHP gives full freedom to use it and develop web projects fast and secure. There is nothing divided in data types because each every variable you can write with $ sign and use that variable for any kind of data, even if it is Integer, String or Decimal. There are few rules to defines variables in php such as

  1. Variable must be alphanumeric.
  2. Starts with alphabets ($name), cannot starts with integer ($1name).
  3. Can use upper case or lower case alphabets.
  4. Always starts with $ sign.

There are 2 types of variables available in php

  1. Static Variables :

Static variable can define and use inside of a page and functions those can initialize and destroy inside the functions.

  1. Global Variables:

Global variables written bite reserve keyword global such as (global $name) this can be use outside of a function or inside of a function. These variables can define anywhere in the project and can use in other functions and classes.

 

Statements: php supports many statements to manage your decisions and process of the project such as if else, switch case, break, continue etc.

If statements is called conditional statements, when you need to take decisions about your work flow to manage project needs and results.

Basic Syntax of “if”;

<?php

$a=5;

$b=8;

If($a>$b){ echo “ any statement or write code to proceed further”}else{ “do this”;}

?>

You can use nested “if else” to take deeper decisions such as

<?php

$a=5;

$b=8;

If($b>$a){

If($b<10){ echo “do this”;}else{echo “do that”;}

}else{ echo “ else do here”;}

?>

Switch Case: we can use switch case also to take decisions but its better to use switch case for so many decisions for single values such as:

<?php

$color=”green”;

Switch($color){

Case “red”:

echo(“given color is red”);

break;

Case “blue”:

echo(“given color is blue”);

break;

Case “green”:

echo(“given color is green”);

break;

 

Default:

//here will come default statement if any of the above conditions are not true then it will print this.

Break;

}

?>

As you can see there are few “Case” and “break” to print correct result of given color variable.

Break is used to discontinue the code and print result. If we not use break after every “Case” code will continue executing and it can give wrong results so we use “break” statement to execute only matching condition and break the process and print result.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x