PHP Array

Let's create an array variable which will hold four different numbers and one string type. Using the syntax from example in the info graphic above, we have:

$numbers = array(42, 12, 1983, 7, "I'm a string"); print_r( $numbers ); //print_r() function is used to print the arrays /* output: Array ( [0] => 42 [1] => 12 [2] => 1983 [3] => 7 [4] => I'm a string ) */

Each number is identified by a key. The key count starts from zero, so the number 42 is identified by key [ 0 ]. If we wanted to print out the value 42, we would type:

echo $numbers[0]; //output: 42

Having unique key identifiers makes it easier to access array's values, just remember to always refer to the array's key when trying to access a particular value. If we tried to use echo on $numbers we would get a Notice from PHP, because it doesn't know what key/value pair we are trying to access:

echo $numbers; //Notice: Array to string conversion

We can also create numeric arrays by manually created the index keys and assigning values to them using the => rocket operator, instead of letting PHP automatically create keys for us.

//The following is identical to previous example: $numbers = array(42, 12, 1983, 7); $numbers = array(0 => 42, 1 => 12, 2 => 1983, 3 => 7);

Associative Arrays

Associative arrays also known as named arrays have string keys instead of numeric keys. Let's use the example similar to the info graphic with some people's names and ages as an example. Note the use of => (rocket) to assign array's key to it's value.

$people = array('Wallace' => 21, 'Victoria' => 22, 'Roman' => 33, 'Alex' => 35, 'Sarah' => 28); print_r( $people ); /* output: Array ( [Wallace] => 21 [Victoria] => 22 [Roman] => 33 [Alex] => 35 [Sarah] => 28 ) */

And if we wanted to access one of the values, we would use the key name in the same way as numeric arrays, though in this case the key must be inside the quotes:

echo $people['Sarah']; //output: 28

Mixed Array

The array doesn't have to be either numeric or associative, it can be both:

$random = array('Keanu Reeves', 'movie' => 'The Matrix', 1999, 5 => "I'm confused", "Hi there"); print_r( $random ); /* output: Array ( [0] => Keanu Reeves [movie] => The Matrix [1] => 1999 [5] => I'm confused [6] => Hi there ) */

There are some things going on in the above example which may cause confusion. One important thing to remember is that the automatic array key indexing picks up the count from the highest numeric key. So when we used 'movie' as a string named key, the value 1999 go assigned the next number from 0 which is 1. And when we set the count to 5, by using 5 => "I'm confused", the next value "Hi there" got assigned a value of 6 which is obviously the next one after 5.

New Medical Assisstant Schools