Previous | Home | Next |
An array is a data structure. it's stores one or more values in a single value. In PHP Programming the programmers are using arrays are actually maps (each key is mapped to a value).
Numerically Indexed Arrays
If you first time seeing an array, then you have not quite understand the concept of an array. so, let's 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, and we show you how below.
PHP Code: <?php $emp_array[0] = "AMIT"; $emp_array[1] = "AKASH"; $emp_array[2] = "ANIKET"; $emp_array[3] = "ARUN"; ?>
This example show the key / value structure of an array.The keys are a numbers that we specified in the array and the values are the names of the employees. Each key of an array represents a value that we can manipulate and reference.
The general form for setting the key of an array equal to a value is:
$array[key] = value;
If we wanted to reference the values that we stored into our array, the following PHP code would get the job done.
PHP Code: <?php echo "MY COMPANY TWO EMPLOYEE " . $emp_array[0] . " & " . $emp_array[1]; echo "<br />ANOTHER Two more employees for my COMPANY" . $emp_array[2] . " & " . $emp_array[3]; ?>
Output:
Two of my employees are Amit & Akash Two more employees of mine are Aniket & Arun
PHP Associative Arrays
An Associative array a key is associated with a value. If we wanted to store in our company employees salaries in an array, then you a numerically indexed array would not be the best choice. Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary.
PHP Code: <?php $sal ["Amit"] = 12000; $sal ["Akash"]=14000; $sal ["Abhinav"] =16000; $sal ["Arun"] =10000; echo "Amit is being paid - $" . $sal ["Amit"] . "<br />"; echo "Akash is being paid - $" . $sal ["Akash"] . "<br />"; echo "Abhinav is being paid - $" . $sal ["Abhinav"] . "<br />"; echo "Arun is being paid - $" . $sal[ "Arun"]; ?>
Output:
Amit is being paid - $12000 Akash is being paid - $14000 Abhinav is being paid - $16000 Arun is being paid - $10000
Once again, the usefulness of arrays will become more apparent once you have knowledge of for and while loops.
Previous | Home | Next |