3

I have an array:

<?php
// My PHP version is 5.3.5
$arr = array("num"=>6,"book"=>"Polyanna","name"=>"Fred","age"=>8)
?>

How do I list the category's in the array and their values, to result something like this:

num: 6
book: Polyanna
name: Fred
age: 8

1
  • 2
    Really, this is basic php that is not worth anyone's time to answer. Even the most horrible of php tutorials can show you how to do this. If this is your first day using php then take some time to read up on it and experiment yourself. I am surprised that you can even ask this with the amount of time you have spent on this site (judging by your reputation). Commented Apr 17, 2011 at 5:55

3 Answers 3

4

First, you can't write arrays like that in PHP. You need to use this notation:

<?php
$arr = array('num' => 6, 'book' => 'Polyanna', 'name' => 'Fred', 'age' => 8);
?>

To list as you described, a foreach loop will suffice:

<?php
$final_str = "";
foreach ( $arr as $key => $value ) {
    $final_str .= $key . ": " . $value . "\n";
}
?>

Or, if you just need to echo the data:

<?php
foreach ( $arr as $key => $value ) {
    echo $key . ": " . $value . "\n";
}
?>
Sign up to request clarification or add additional context in comments.

Comments

1

You want foreach.

1 Comment

This answer looks more like a comment.
1

You need => instead of = while declaring array

$arr = array("num"=>6,"book"=>"Polyanna","name"=>"Fred","age"=>8)

and iterate through foreach loop to retrieve values

foreach ($arr as $key => $value)
{
   echo $key. ":". $value;
}

Comments

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.