Matthew Underwood
Matthew Underwood

Reputation: 1499

Foreach loop, using key identifers in one single array

I am using key identifers in my foreach loop in order to control how I echo strings next to the data. For example

The array

  $array = array("name" => "Jim", "age" => 34);

array(2) {
  ["name"]=> string(3) "Jim"
  ["age"]=>  int(34)
}

The loop

<?php
 foreach ($array as $value) {

  echo "Name " .$value["name"]."</br>
    Age ".$value["age"] . "</br>";

 }
?>

The output I get

Name J
Age J
Name
Age 

The desired result

Name Jim 
Age 34

Upvotes: 0

Views: 481

Answers (5)

Surace
Surace

Reputation: 711

 <?php
   foreach ($array as $key => $value) {
    echo ucfirst($key).' '.$value.'<br />';
   }
?>

Upvotes: 1

SubjectCurio
SubjectCurio

Reputation: 4872

you don't need a foreach loop for what you're trying to accomplish, it would be as simple as:

$array = array("name" => "Jim", "age" => 34);

echo "Name " . $array["name"] . "</br>";
echo "Age " . $array["age"];

Upvotes: 0

Chris
Chris

Reputation: 5605

You can do that without a for loop...

<?php

  $array = array("name" => "Jim", "age" => 34);
  echo "Name " .$array["name"]."</br>
    Age ".$array["age"]. "</br>";

 }

?>

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361595

Get rid of the foreach loop:

echo "Name " . $array["name"] . "</br>\n"
   . "Age "  . $array["age"]  . "</br>\n";

Or, if you want to loop over multiple people, you need to make a nested array of arrays.

$people = array(
    array("name" => "Jim", "age" => 34),
    array("name" => "Bob", "age" => 42)
);

foreach ($people as $person) {
    echo "Name " . $person["name"] . "</br>\n"
       . "Age "  . $person["age"]  . "</br>\n";
}

Upvotes: 2

thatidiotguy
thatidiotguy

Reputation: 8991

Why are you using the foreach functionality? If you remove that you will get exactly what you want. And you will change $value to $array.

Upvotes: 1

Related Questions