change original array values inside foreach php - php

I want to update an array inside foreach I tried this two code :
code 1 :
foreach ($listOrders as $k => $order) {
foreach ($listOrders as $key => $o)
{
if ($o["id_order"] == $order["id_order"])
{
unset($listOrders[$key]);
}
}
in this codeunset is not working
code 2 :
foreach ($listOrders as $k => &$order) {
foreach ($listOrders as $key => $o)
{
if ($o["id_order"] == $order["id_order"])
{
unset($listOrders[$key]);
}
}
If I use & with $order $listOrders will not returned all data that I want.

Your error should be here
foreach ($listOrders as $k => &$order) {
^
Remove &
Also you are iterating through your $listOrders twice with your code, won't your array list always be empty after the iteration is finished?

If you are simply trying to get a list of the orders in the list, you can use array_column() to index the list by id_order. As you can only ever have 1 entry in an array with a particular key, this will end up with the last entry with a particular order id in the array...
$uniqueList = array_column(listOrders, null, "id_order");
If you just need the list without the index, you can use array_values() to re-index the list.
$uniqueList = array_values(array_column(listOrders, null, "id_order"));

Related

Bug when trying to update an array

I have a two questions with a symfony's project.
My first one :
I am trying to modify some data in an array.
I have this code
var_dump($results); // FIRST ONE
foreach ($results as $result) {
foreach ($result as $res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
var_dump($res); // THIS ONE IS MODIFIED
}
}
var_dump($results); // LAST ONE... SAME AS THE FIRST ONE
I don't understand why my array ' $results ' is no updated... am i missing something ?
And my second question : is there any way to simplify this code ? I don't like the 3 foreach.
Thanks you guys :)
PHP foreach copy each item when iterate so $result array will not update when you change $res item.
1) You can use array keys to change main array
foreach($arrr as $k => $item) {arrr[$k]['key'] = 'changed'}
2) Or you can get link to the $res item and change it dirrectly
foreach($arrr as &$item) {$item['key'] = 'changed'}
Note that second case can cause different issues
Unless you're passing an object in PHP, PHP does not pass values by reference. $res is a copy of the value, not a link to the original value. If you know what you're doing, you can pass by reference. When passing by reference, altering $res would alter the original data. You pass by reference by prefixing a & to the variable or argument.
Since this is a nested foreach, you'll also have to pass $result by reference to avoid that being a copy of the item of $results.
foreach ($results as &$result) {
foreach ($result as &$res) {
foreach ($dates as $date) {
if(!array_key_exists($date,$res)) {
$res = array_merge($res,[$date => '0']);
}
}
}
}

How to get every key-value-pair from PHP-array

I need to get every key-value-pair from an array in PHP. The structure is different and not plannable, for example it is possible that a key contains an additional array and so on (multidimensional array?). The function I would like to call has the task to replace a specific string from the value. The problem is that the function foreach, each, ... only use the main keys and values.
Is there existing a function that has the foreach-function with every key/value?
There is not a built in function that works as you expect but you can adapt it using the RecursiveIteratorIterator, walking recursively the multidimensional array, and with the flag RecursiveIteratorIterator::SELF_FIRST, you would get all the elements of the same level first, before going deeper, not missing any pair.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $item) {
// LOGIC
}
The usual approach to this kind of task is using a recursive funcion.
Let's go step by step:
First you need the foreach control statement...
http://php.net/manual/en/control-structures.foreach.php
..that let you parse the associative array without knowing keys' names beforehand.
Then is_array and is_string (and eventually is_object, is_integer...) let you check the type of each value so you can act properly.
http://php.net/manual/en/function.is-array.php
http://php.net/manual/en/function.is-string.php
If you find the string to be operated then you do the replace task
If you find an array the function recalls itself passing the array just parsed.
This way the original array will be parsed down to the deepest level without missing and key-value pair.
Example:
function findAndReplaceStringInArray( $theArray )
{
foreach ( $theArray as $key => $value)
{
if( is_string( $theArray[ $key ] )
{
// the value is a string
// do your job...
// Example:
// Replace 'John' with 'Mike' if the `key` is 'name'
if( $key == 'name' && $theArray[ $key ] == "John" )
{
$theArray[ $key ] = "Mike";
}
}
else if( is_array( $theArray[ $key ] )
{
// treat the value as a nested array
$nestedArray = $theArray[ $key ];
findAndReplaceStringInArray( $nestedArray );
}
}
}
You can create a recursive function to treat it.
function sweep_array(array $array)
{
foreach($array as $key => $value){
if(is_array($value))
{
sweep_array($value);
}
else
{
echo $key . " => " . $value . "<br>";
}
}
}

PHP removing elements from array in a foreach loop

I'm trying to unset() some elements from an array but when using a foreach loop to go through 1 array to delete these elements from another array it does not seems to be working.
if (isset($this->request->post['merge'])) {
$merge_orders = $this->request->post['merge'];
}
$selected_order = min($merge_orders); // Fetch the max value order_id
unset($merge_orders[$selected_order]); // Take it out of the array.
$orders_list = explode(',', $this->request->post['order_id_list']);
$removeKeys = $merge_orders;
foreach($removeKeys as $key) {
unset($orders_list[$key]);
echo $key;
}
echo print_r($orders_list);
The first unset works fine but the second does not, the array is set and properly formatted but it still does not seem to remove the elements from the $orders_list array.
If you only use one parameter on a foreach loop you are delivered the value of the occurance and not the key for the occurance.
Try this so that you are getting a key from the foreach loop and not a value
foreach($removeKeys as $key => $val) {
unset($orders_list[$key]);
echo $key;
}

PHP Array reference, modifying array values

I'm trying to modify an array when looping through it and increment certain values.
$data = ['traits' => [[['amt' => 1]]]];
var_dump($data['traits']);
foreach ($data['traits'] as $key => &$index) {
foreach ($index as $key => &$value) {
$value['amt'] = $value['amt']++; // This should increment
if (in_array($key, $input)) {
$i++;
$insert["field_".$i] = $key."_1";
}
}
}
var_dump($data['traits']); // SAME AS PREVIOUS VAR_DUMP
What you are doing in the loop is undefined:
$value['amt'] = $value['amt']++;
The outcome of that depends on what's evaluated first. In this case $value['amt']++ seems to be evaluated first and then assigned to $value['amt'] again; the side effect of the increment is lost.
On the other hand, the following statement will work as expected:
$value['amt']++;

php update values of an array based on other array with the same key

I have the following scenario:
$starterArray = array ('192.168.3.41:8013'=>0,'192.168.3.41:8023'=>0,'192.168.3.41:8033'=>0);
In the requirement I have another array which counts some events of the application, this array uses the same keys as my first array, but values can change), so at the end I could have something like:
$processArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I want to update the values of my starter array with the values of the process array, for instance, at the end, I should have:
$starterArray = array ('192.168.3.41:8013'=>3,'192.168.3.41:8023'=>5,'192.168.3.41:8033'=>7);
I know this can be achieved by using $starterArray = $processArray;
Then in some moments, I would need to sum some units to the values of my array, for example +1 or +2:
It should be something like the following?
foreach ($starterArray as $key => $value) {
$starterArray[$value] = $starterArray[$value]+1;
}
Then, for my process array, I need to set the values to 0
foreach ($processArray as $key => $value) {
$processArray[$value] = 0;
}
This is what I tried but it is not working, if somebody could help me I will really appreaciate it. Thanks in advance.
PD: I know these are strange requirements, but that's what I am asked to do...
You are almost there:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
}
and then:-
foreach ($processArray as $key => $value) {
$processArray[$key] = 0;
}
However, you could do this all in one loop:-
foreach ($processArray as $key => $value) {
$starterArray[$key] = $value +1;
$processArray[$key] = 0;
}
You need to put $key in brackets, not $value.
Or, you can do:
foreach ($starterArray as $key => &$value) {
$value++; /* put here whatever formula you want */
}
foreach ($starterArray as $key => $value) {
$starterArray[$key] = $value+1;
// or $starterArray[$key] = 0;
}

Categories