Friday, 04 September 2020

Create an array and access array elements in 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().


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.




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");
echo "<br>";

The output will be:

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

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");
echo "<br>";
print_r($student["First Name"]);
echo "<br>";

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 )

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>";


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

Create an array of objects

If you want to create an array of objects, you can do like this:

class Car {
    public $brand;
    public $model;
    public $color;

$cars = array();
$cars[0] = new Car;
$cars[0]->brand = 'Honda';
$cars[0]->model = 'Jazz';
$cars[0]->color = 'Blue';

$cars[1] = new Car;
$cars[1]->brand = 'Toyota';
$cars[1]->model = 'Yaris';
$cars[1]->color = 'White';

In the above code snippet, class Car is defined followed by the initialization of the array of objects

$cars = array();

Here, we create two sample objects in $cars[0] and $cars[1]. To loop through this array of objects, you can do as follows:

foreach ($cars as $key => $obj) {
    echo "{$key}: {$obj -> brand}<br>";
    echo "{$key}: {$obj -> model}<br>";
    echo "{$key}: {$obj -> color}<br>";

The output is:

0: Honda
0: Jazz
0: Blue
1: Toyota
1: Yaris
1: White