PHP question about multidimensional array

My array looks like this:

Array ( [Bob] => Red [Joe] => Blue )

But it can be any number of people, for example:

Array ( [Bob] => Red [Joe] => Blue [Sam] => Orange [Carla] => Yellow)

Basically, I want PHP to take this array and repeat it so that it looks like this:

Bob - Red
Joe - Blue
Sam - Orange
Carla - Yellow

I know that I need to go through an array, here is what I tried:

for ($row = 0; $row < count($array); $row++) {
echo $array[0] . " - " . $array[1];
}

I get the following error: Undefined offset: 0, Undefined offset: 1

I understand that this does not work, because I am trying to use the index when the array values ​​are strings. Is there a way to use a positional index like this with a multidimensional array that contains only rows?

thank

+3
source share
3 answers

What you want is a loop foreach.

foreach ($array as $key => $value) {
    echo $key . ' - ' . $value;
}

( , "\n" )

.

array(
    array(
        'bob',
        'tom'
    )
);

.

.

+7

php:

foreach($array as $key => $value) {
    echo "$key - $value<br />\n";
}
+2

You need foreach

<?php 
$arr = array("bob" => "red", "paul" => "blue", "preo" => "yellow", "garis" => "orange");
foreach ($arr as $key => $value) {
    echo $key ." - ".$value."<br />";
}
?>

It will be printed:

bob - red
paul - blue
preo - yellow
garis - orange

By the way, this is an array associative, not multidimensionalone, which is more like:

$array[1][0][3]
+1
source

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


All Articles