Reputation: 1499
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
Reputation: 711
<?php
foreach ($array as $key => $value) {
echo ucfirst($key).' '.$value.'<br />';
}
?>
Upvotes: 1
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
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
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
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