Friday 13 May 2011

PHP Tutorials For Dummies | Arrays()

Arrays in PHP are very useful variables which can hold more than one data item. Imagine that you own a business and you want to store the names of all your employees in a PHP variable. It wouldn’t make much sense to have to store each name in its own variable. Instead, it would be nice to store all the employee names inside of a single variable. This can be done with array .
Example 1 :How To Create Arrays Without Setting Key Values
PHP Code:

<?php

$arrVar =array(“Ivan” , “David, “John” );
echo $arrVar[0] . “<br> “;
echo $arrVar[1] . “<br> “;
echo $arrVar[2] . “<br> “;
?>
OUTPUT :
Ivan
David
John
In example 1 we created an array called $arrVar , that array contains 3 items : Ivan , David , John . To access, modify, insert items in array we use keys that are automatically(not always) set as a numeric values 0,1,2 …… as shown on image below.This means that Ivan in the array has the key 0, and the array item David lives at key 3.

Example 2 : How To Create Arrays With Setting Key Values
PHP Code:

<?php
$arrVar =array("name1"=>"Ivan" , "2"=>"David", "name3"=>"John" );
echo $arrVar[name3] . "<br> ";
echo $arrVar[2] . "<br> ";
echo $arrVar[name1] . "<br> ";
?>

OUTPUT :
John
David
Ivan
In example 1 the key value is automatically set as a numeric value, we can however change the key and set our own, like above.
Ivan in the array has the key name1, John has the key 2 and the array item David has the key name3.

Example 3: How To Create Multidimensional Array
Array does not have to be a simple list of keys and values; each array element can contain another array as a value, which in turn can hold other arrays as well. In such a way you can create multi-dimensional array.
PHP Code:

<?php
$arrVar =array ("editors"=>array("1"=>"Tommy" , "2"=>"David", "3"=>"John" ) ,
"admin"=>"Ivan",
"website"=>"hackspc.com"

);

echo $arrVar[editors][1] . “<br> “;
echo $arrVar[editors][3] . “<br> “;
echo $arrVar[admin] . “<br> “;
echo $arrVar[website] . “<br> “;
?>
OUTPUT:
Tommy
John

Ivan
hackspc.com

Example 4: How To Use Loops to display array elements
<?php
$arrVar =array("Ivan" , "David", "John" );
foreach ($arrVar as $item)
{
echo $item . "<br> ";
}
?>
OUTPUT:
Ivan
David
John
PHP provides an easy way to use every element of an array with the Foreach statement. For each item in the specified array execute this code.
While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.

No comments:

Post a Comment