views:

63

answers:

3

My array looks like this:

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

But it could be any number of people, like this:

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

Basically I want PHP to take this array and echo it so that it comes out looking like:

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

I know I need to loop through the array, this 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 realize that this doesn't work because I'm trying to use index's when the values of the array are strings. Is there any way I can use positional index's like this with a multidimensional array that only contains strings?

Thanks

+7  A: 

What you want is a foreach loop.

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

(if you want a newline, append "\n" to the end)

Your array is actually not multidimensional. An example of that would be

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

Note the array within the array.

Your array is generally called an associative array.

alex
You should probably use `\n` as well.
too much php
+2  A: 

Without re-checking my php knowledge:

foreach($array as $key => $value) {
    echo "$key - $value<br />\n";
}
David Thomas
You should probably use `\n` as well.
too much php
@too much php, there is that, yeah. Thanks! (edited.)
David Thomas
+1  A: 

You need a foreach

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

Will print:

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

By the way, it is a associative array, not a multidimensional one, which is more something like:

$array[1][0][3]
Garis Suero
Ah this works beautifully. Thank you for your response, no wonder I couldn't find anything that would work -- I kept searching for multidimensional
Sam