php

Define array PHP

In this code example, we are describing how you can define an array in PHP.

<?php
    //DEFINE INDEXED ARRAY METHOD 1
    $array = array("Math", "Physics", "Checmistry");

    //DEFINE INDEXED ARRAY METHOD 2
    $array = ["Math", "Physics", "Checmistry"];

    //DEFINE ASSOCIATIVE ARRAY METHOD 1
    $array = array(
        "name" => "John",
        "profession" => "Programmer",
        "lang" => "PHP"
    );

    //DEFINE ASSOCIATIVE ARRAY METHOD 2
    $array = [
        "name" => "John",
        "profession" => "Programmer",
        "lang" => "PHP"
    ];
?>

In PHP you can define an array as an Indexed array or an associative array. Indexed array values can be accessed via index and associative array values can be accessed via its corresponding key name.

In the code snippet, we have defined both types of arrays. And if you want to access the value of the Indexed array you can use syntax.

<?php
    echo $array[3];
?>

To get the value of associative array use Syntax

<?php
    echo $array['name']
?>

Loop through arrays examples

You can loop through arrays and get keys and values of an indexed and associative array. Below is the code example for both

<?php
    $fruits = ["apple", "banana", "orange"];
    foreach($fruits as $key => $value) {
        echo $key . " : " . $value; 
        //$key will be 0, 1, 2 and $value apple, banana, orange
    }

    $fruit = [
        "name" => "apple",
        "qty"  => 50,
        "type" => "seasonal"
    ];
    foreach($fruit as $key => $value) {
        echo $key . " : " . $value; 
        //$key will be name, qty, type and $value apple, 50 and seasonal
    }

    $fruits = [
        [
            "name" => "apple",
            "qty"  => 10,
            "type" => "seasonal"
        ],
        [
            "name" => "banana",
            "qty"  => 20,
            "type" => "seasonal"
        ]
    ];
    foreach($fruits as $key => $value) {
        echo $value["name"];
    }
?>
<?php
    // One dimensional array [With values only]
    $array = [10, 20, 30, 40];
    echo $array[2];  // -> 30

   // One dimensional array [With key, value]
   $arr = [
        'name' => 'Rick Grimes',
        'address' => 'Alexendria',
        'son' => 'Carl'
    ];

    echo $arr['name'];
?>
This is an example of making one dimenstional array in PHP and printing its elements using index and key name.
Was this helpful?