Chrome Extension

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"
    ];
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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"];
    }
?>
Was this helpful?
0 Comments
Join Devsheet Ask a Question