Tuesday, June 18, 2013

php arrays

php arrays
What is an array, array in php is a variable which can store many values, there are three types of php arrays

  • Numeric array : array with a numeric index
  • Assosiative array : array where their values indexed with specific ID
  • Multidimensional array : array containing many arrays
We can define php arrays like this,
$names = array("john","lora","maria");
In this example we define an array called "names" and we store three values in it, if we want to print one of the values for example the first one we should write this code
echo $names[0];
We should see john on the screen and as you notice the index of the first value is 0, what we should write if we want to print the third value
echo $names[2];
php arrays
This was the explanation of the Numeric array, now let's talk about Assosiative array
We can define Assosiative array like this
$names = array("j"=>"john","l"=>"lora","m"=>"maria");
In this example we define an Assosiative array with three values and each value have a key 
Let's see how we can call the values in this array

echo $names["j"];
echo $names["l"];
echo $names["m"];
We will see this in the screen
johnloramaria

Now let's talk about the third type of php arrays the Multidimensional array, let's take an example

$names = array (
"name1"=>array("john","julia"),"name2"=>array("lora","lisa"),"name3"=>array("maria")
);
The global array called names and inside of it there are three arrays name1,name2,name3 every array from these arrays have diffrent values, so if we want to print the first value of the first array we should write this
echo $names['name1'][0];
And if we want to print the second value of the second array we should writs this
echo $names['name2'][1]

This was the php arrays lesson i hope you enjoy it, if you have any question just leave a comment
See you next time.

Share This!



No comments :

Post a Comment