Monday, April 13, 2015

Main PHP Data Types

Main PHP Data Types
This is A quick post to understand datatypes in the PHP 
and those are complex to understand are only included below with little explanation. :)
PHP supports the following data types:
  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • Resource
  • NULL

Integer

mainly, It is a number between -2,147,483,648 and +2,147,483,647.
Boolean
A Boolean shows two possible states: TRUE or FALSE.
$a = true;
$b = false;
Booleans are mostly used in conditional testing. 

Array
to stores multiple values in one single variable.
PHP NULL Value
Null is a special data type which can have only one value, NULL.
A variable of data type NULL,no value assigned to it.
Note: If a variable, without a value, it is automatically assigned a value of NULL.
Variables can also be emptied by setting the value to NULL:
Example
<?php
$a = "Hello universe.!";
$b = null;
var_dump($a);
?>


Resource

not an actual data type. It stores the reference of functions and external resources  to PHP.

Example:  database call.



PHP-Loop

PHP Loops

When you write code, we want the same block of code to run over and over in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this.
In PHP, we have the following looping statements:
  • while – repeat through a block of code as long as the specified condition is true
  • do...while - repeat through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - repeat through a block of code a specified number of times
  • foreach - repeat through a block of code for each element in an array

 

while Loop


The ex. shows first sets a variable $y to 1. Then, the while loop will continue to run upto $y is less than, or equal to 4 ($y <= 4). $y will increase by 1 every time the loop runs ($y++):
Example:
<?php 
$y = 1;
 

while($y <= 4) {
    echo "The number is: $4 <br>";
    $x++;
}
 
?>
o/p:

The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 



Do_while Loop:


 Same as while just execution of condition after do part means, after a block of code.


<?php
$y = 1;

do {
    echo "The number is: $y <br>";
    $y++;
} while ($y <= 5);

?>

o/p:

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

if you want in certain case, your code to be executed once either condition is true or false then, do while loop is the way to use. 
in following example shows such condition,

<?php 
$a = 7;

do {
    echo "The number is: $a <br>";
    $a++;
} while ($a<=6);
?

O/P:
The number is: 7 

even if condition is false but, value of $a=7 has been printed once.