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

1
  • 1
    I think that's an associative array, not multidimensional... Commented Sep 16, 2010 at 4:10

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You should probably use \n as well.
2

Without re-checking my php knowledge:

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

1 Comment

You should probably use \n as well.
1

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]

1 Comment

Ah this works beautifully. Thank you for your response, no wonder I couldn't find anything that would work -- I kept searching for multidimensional

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.