Friday, 04 September, 2020

How to create an array and access an array element in PHP

PHP 

In PHP, we can create indexed and associative arrays, where integer and string can be used as keys respectively.

Indexed array

You can use the function array() to create an array.

$animal = array("dog", "cat", "sheep", "rabbit", "pig");

In the above example, PHP automatically assigns a numeric index to each element. To print out the details of the array $animal, you can use the function print_r().

print_r($animal);

The above code will output:

Array ( [0] => dog [1] => cat [2] => sheep [3] => rabbit [4] => pig ) 

As you can see, the index starts from 0 and increase by 1 for each element. You can use the array[key] syntax to access array elements.

print_r($animal[2]);

Output:

sheep

Or you can define your own numeric index explicitly for each array elements.

$animal = array(5=>"dog", 8=>"cat", 9=>"sheep", 14=>"rabbit", 15=>"pig");
print_r($animal);
echo "<br>";
print_r($animal[14]);

The output will be:

Array ( [5] => dog [8] => cat [9] => sheep [14] => rabbit [15] => pig )
rabbit

Associative array

You can also create an array in an associative style, where you can use your own string as a key for each element. With this kind of array, you can store data like using a database.

$student = array("First Name"=>"Emma", "Last Name"=>"Brown", "Age"=>12, "Class"=>"6H");
print_r($student);
echo "<br>";
print_r($student["First Name"]);
echo "<br>";
print_r($student["Age"]);

In the above code snippet, the variable $student stores a student's personal data with different keys: "First Name", "Last Name", "Age" and "Class".
The output will be:

Array ( [First Name] => Emma [Last Name] => Brown [Age] => 12 [Class] => 6H )
Emma
12

Loop through an array

To iterate over the whole array, PHP's foreach loop is a convenient way.

$student = array("First Name"=>"Emma", "Last Name"=>"Brown", "Age"=>12, "Class"=>"6H");

foreach ($student as $key => $value) {
    echo "{$key}: {$value}<br>";
}

Output:

First Name: Emma
Last Name: Brown
Age: 12
Class: 6H

Search
Tags

PHP