First of all I have searched for the similar threads on StackOverflow like this one
$myvar = array ("key_name" => array("tom", "an", "bob"),
"key_age" => array("1", "10", "12")
);
I have tried lot of things but I couldn't
foreach($myvar as $i){
foreach ($i as $key => $value) {
echo print_r($i);
}
I am trying to get "key_name" and loop through it
<?php
$myvar = array (
"key_name" => array("tom", "an", "bob"),
"key_age" => array("1", "10", "12")
);
foreach ($myvar['key_name'] as $value) {
echo $value;
}
Result:
tomanbob
https://3v4l.org/tEFvS
If you want to loop through both:
foreach ($myvar as $sub_array) {
foreach ($sub_array as $value) {
echo $value;
}
}
Result:
tomanbob11012
https://3v4l.org/cMFUh
Check out, http://php.net/manual/en/control-structures.foreach.php for info on using foreach
You can use array_walker. So you can do something like this :
array_walk($myvar,function($sub_items,$key){
echo "Key is >> " . $key . "\n";
foreach($sub_items as $item){
echo $item . "\n";
}
echo "------------ \n ";
});
Note:
I put an echo with a new line to understand how to implement that!
Related
I'm trying out the following code for arrays in php, I create a associate array, print out the values and add one more to the array - print out again. This works, but if I try the foreach ($MovieCollection as $key => $value) it does not print out the values. Why does it not do that?
$myArray = array("Star Wars", "The Shining");
foreach ($myArray as $val)
{
echo("Movie: " . $val ."<br>");
}
$MovieCollection = array();
$MovieCollection[] = array('title' => 'Star Wars', 'description' =>'classic');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
$MovieCollection[] = array('title' => 'The shinning', 'description' =>'creepy');
foreach ($MovieCollection as $film )
{
echo($film['title'] .": " . $film['description'] ."<br>");
}
echo("<br><br>");
// This does not print the values?
foreach ($MovieCollection as $key => $value)
{
echo($key .": " . $value ."<br>");
}
That is because in this part $MovieCollection is an array of arrays and if you want to echo the $value which is an array, you will do an Array to string conversion which does not work.
What you might do is use another foreach to show the values per array:
foreach ($MovieCollection as $value) {
foreach ($value as $k => $v) {
echo($k .": " . $v ."<br>");
}
}
See a Php demo
this code works as expected
$fruits = array("d" => "Zitrone", "b" => "Banane", "c" => "Apfel");
$fruits["a"] = "Orange";
//print_r($fruits);
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
ok, now I would like to do the same programmatically:
$collection = array();
foreach ($xml->abschnitte[0]->abschnitt as $sec) {
//echo $sec['strecke']; // this works, the strings are printed out
$collection[$sec['strecke']] = $sec['id'];
}
//print_r($collection); // nothing to see here
//ksort($collection);
foreach ($collection as $key => $val) {
echo $key . " = " . $val . "\n";
}
it seems that there no collection will be build. but there must be a way to build the key up from variables. what do i miss? thanks in advance, mischl
I'm from Perl but I'm beginner in PHP. I'm having following array
$rating_data = Array ("51" => Array (5,3,4,2));
I'm trying to access the each data using loop so I tried following
foreach ($keys as $rating_data)
{
foreach ($index as $rating_data[$keys])
{
echo "$index";
}
}
But the above one is not working. I have also tried the below one also,
$all_keys = array_keys($rating_data);
foreach ($keys as $all_keys)
{
foreach ($values as $all_keys)
{
echo "$values";
}
}
But I didn't get the output. It works if I hard code the keys like below:
$rating_data["51"][0];
How to fix this issue.?
You can get the key position and iter value ( sencod level ).
foreach($rating_data as $key => $values)
{
echo $key; // Output "51"
foreach($values as $value)
{
echo $value; // Output: iter1: "5", iter2: "3", iter3: "4", iter1: "2",
}
}
It should be as simple as below:
foreach($rating_data as $key => $values) {
echo $key;
foreach($values as $value) {
echo $value;
}
}
You seem to have your parameters the wrong way around in your foreach statements. I would advise a quick read through the foreach docs.
Below is a simple array that I created:
$colors = array(
"parent1" =>array(
"item1"=>"red",
"item2"=>"green",
"item3"=>"blue",
"item4"=>"yellow"
),
"parent2" =>array(
"item1"=>"red",
"item2"=>"green",
"item3"=>"blue",
"item4"=>"yellow"
)
);
What I need to get is the key of my level 1 arrays which are string "parent1" and "parent2".
Currently I'm using foreach with while loop to get the key
foreach ($colors as $valuep) {
while (list($key, $value) = each($colors)) {
echo "$key<br />";
}
}
but I'm only able to get the "parent2" string from using the above method and not "parent1".
You're so close.
foreah($colors as $key => $val)
{
echo $key . "<br/>";
}
Use the key like so:
foreach ($colors as $key => $value) {
echo $key.'<br>';
}
To print out the keys:
foreach ($colors as $key => $value) {
echo $key . '<br />';
}
You can also get all of the keys from an array by using the array_keys() method, for example:
$keys = array_keys($colors);
foreach ($keys as $key) {
echo $key . '<br />';
}
I am trying to print an array using foreach and while printing, if a certain $key comes up, I want to make changes to the array. Problem is, even though the array gets changed, the changes do not get printed.
In the example below, you will find:
function I use to change the array;
an array first printed with no changed;
then echo print-out in with changes during the process - all using foreach;
another print-out of the same table, but this time with changes.
<?php
function insert_before_key($array, $key, $data = NULL){
if (($offset = array_search($key, array_keys($array))) === false){
$offset = count($array);
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
echo "<pre>";
print_r($array);
echo "</pre>";
foreach ($array as $key => $value) {
echo $key . ": " . $value . "<br />";
if ($key === "color1"){
$array = insert_before_key($array, "color2", array("color1.5" => "yellow"));
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
echo "<br />";
?>
Note that the new $key is to jump in AFTER current $key, so I would expect it to come up.
Any idea why this happens ?
EDIT:
Played a bit more with foreach and I think it must be caching the keys or something...
<?php
$test_array = array(0,1,2,3,4,5,6,7,8,9);
foreach ($test_array as $key => $value) {
if ($key === 5){$test_array[7] = $test_array[7]+1;}
echo $key . ": " . $value . "<br />";
}
print_r($test_array);
?>
The above will display UNCHANGED echo, but CHANGED print_r.
From the manual: "As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior." http://php.net/manual/en/control-structures.foreach.php
You shouldn't modify an array you're looping over.
So during iteration you are trying to change the value of the item being iterated
foreach($array ...)
{
change $array
}
Use a copy of $array inside the iteration
$array2 = $array
foreach($array ...)
{
change $array2
}
I'd keep it simple. Something tells me however that you're fixing effects of a problem here and not its source.
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
$temp_array = array();
foreach ($array as $key => $value) {
$temp_array[$key] = $value;
echo $key . ": " . $value . "<br />";
if ($key == 'color1') {
$key_add = 'color1.5';
$value_add = 'yellow';
$temp_array[$key_add] = $value_add;
echo $key_add . ": " . $value_add . "<br />";
}
}
$array = $temp_array;