foreach doesn't print altered array properly - php

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;

Related

merging json array only with same keys

I have two Json arrays like below:
$a='[{"type":"text","req":0,"name":"user"},{"type":"text","req":0,"name":"org"},'
. '{"type":"textarea","label":"Notes","req":0},'
. '{"type":"text","label":"text1","req":0},'
. '{"type":"textarea","label":"Notes","req":0},'
. '{"type":"text","label":"text2","req":0},'
. '{"type":"textarea","label":"Notes","req":1}]';
$b='[{"type":"textarea","label":"Notes","Element_Values":"331","Element_Name":"textarea-710091","Count_Images":0},'
. '{"type":"text","label":"text1","Element_Values":"1","Element_Name":"text-987351","Count_Images":0},'
. '{"type":"textarea","label":"Notes","Element_Values":"332","Element_Name":"textarea-254458","Count_Images":0},'
. '{"type":"text","label":"text2","Element_Values":"2","Element_Name":"text-3410","Count_Images":0},'
. '{"type":"textarea","label":"Notes","Element_Values":"333","Element_Name":"textarea-554051","Count_Images":0}]';
As you can see array 'a' starts with few keys which is not in array 'b'. I want to skip the arrays which has 'name' keys.
I did the following code, but didnt work:
$c = [];
$aJson=json_decode($a, true);
$bJson=json_decode($b, true);
foreach($aJson as $key => $array)
{
foreach($array as $an)
{
if(array_key_exists('name', $an))
{
//continue;
}
}
$c[$key] = array_merge($bJson[$key],$array);
}
echo json_encode($c);
The result array c should be:
[{"type":"textarea","label":"Notes","Element_Values":"331","Element_Name":"textarea-710091","Count_Images":0,"req":0},{"type":"text","label":"text1","Element_Values":"1","Element_Name":"text-987351","Count_Images":0,"req":0},{"type":"textarea","label":"Notes","Element_Values":"332","Element_Name":"textarea-254458","Count_Images":0,"req":0},{"type":"text","label":"text2","Element_Values":"2","Element_Name":"text-3410","Count_Images":0,"req":0},{"type":"textarea","label":"Notes","Element_Values":"333","Element_Name":"textarea-554051","Count_Images":0,"req":1}]
Please help me
This is a simple debug problem, $array is already the array.
$index = 0;
foreach($aJson as $key => $array)
{
if(isset($array['name']))
continue;
$c[$index] = array_merge($bJson[$index], $array);
$index++;
}

iterate associate array in php does not print out values

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

Confused about how to loop through subArray

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!

php associative array: no array build with key from variable name

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

php built in counter for what iteration foreach loop is currently in

I have an associative array. Two dimensions which I am iterating through like this
foreach ( $order_information as $sector_index => $sector_value ){
echo 'sector : ' . current($order_information) ;
echo '<br>';
foreach ( $sector_value as $line_index => $line_value ){
}
}
The current() is an attempt to get the iteration the loop is in. It seems like this should give me that. However, elsewhere on that page there is the suggestions that you just do like
$index = 0
foreach ( $array as $key => $val ) {
echo $index;
$index++;
}
I wonder if I am using current incorrectly, as echo 'sector : ' . current($order_information); just prints sector : Array
Is $index++ bad syntax? Is there a better way to do this?
Answer
As far as I know there is no build in numeric counter in a foreach loop in PHP.
So you need your own counter variable. Your example code looks quite good to do that.
$index = 0;
foreach($array as $key => $val) {
$index++;
}
By the way, $index++; is fine.
Example
Here is an example illustrating which variable stores which value.
$array = array(
"first" => 100,
"secnd" => 200,
"third" => 300,
);
$index = 0;
foreach($array as $key => $val) {
echo "index: " . $index . ", ";
echo "key: " . $key . ", ";
echo "value: " . $val . "\n";
$index++;
}
The output will be that.
index: 0, key: first, value: 100
index: 1, key: secnd, value: 200
index: 2, key: third, value: 300
Current-Function
I think you misunderstood current($array). It gives you the value pointed by an internal array pointer, which can be moved using next($array), prev($array) and end($array).
Take a look at the manual to make thinks clear.

Categories