How to initialize a two-dimensional PHP array

Let's say I would like to manage a multidimensional array like (pseudocode):

Array $colors
* wine,red
* cheese,yellow
* apple, green
* pear,brown

What code can be used to avoid the following notation for initializing an array (it is assumed that there will be a hard-coded list of elements = ?:

$colors[x][y] = 'something';
+3
source share
4 answers
$array = array(
   array('wine', 'red'),
   array('cheese', 'yellow'),
   array('apple', 'green'),
   array('pear', 'brown')
);

UPD:

foreach ($array as $v) {
   echo $v[0]; // wine, cheese...
   echo $v[1]; // red, yellow...
}
+4
source

Assuming you don't need an associative array, since your question doesn't mention it.

This elegant PHP syntax allows you to:

<?php
$colors = array(array("wine","red"),
                array("cheese","yellow"),
                array("apple", "green"),
                array("pear", "brown"));

print_r($arr); // Prints out an array as shown in output
?>

Conclusion:

    Array
(
    [0] => Array
        (
            [0] => wine
            [1] => red
        )

    [1] => Array
        (
            [0] => cheese
            [1] => yellow
        )

    [2] => Array
        (
            [0] => apple
            [1] => green
        )

    [3] => Array
        (
            [0] => pear
            [1] => brown
        )

)

To iterate over access to all 0:

for($x = 0; $x < count($colors); $x++){
    echo $colors[$x][0];
}

As an alternative

for($colors as $couple){
   echo $couple[0];
}

EDIT: It seems you can really be better with associative though ..

$colors = array("wine"   => "red",
                "cheese" => "yellow",
                "apple"  => "green",
                "pear"   => "brown");

The reason you can still access the keys is:

 for($colors as $key => $value){
       echo $key . " is " . $value;
    }
+3
$colors = array(
    array('wine' => 'red',
        'cheese' => 'yellow',
        'apple' => 'green',
        'pear' => 'brown'
    )
);
0

Source: https://habr.com/ru/post/1768427/


All Articles