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']++;
Related
I have a foreach loop for an array
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
$total += $something['Cost'];
$singleprice = $available['Cost'];
}
I need to be able to return $total and $singleprice - Total adding up all the values within the key, $singleprice returning only 1 instead of all added up
The only way I've managed to return this value is by creating another foreach loop within this foreach loop like so:
foreach ($somethings as $key2 => $something)
{
$value = 0;
if ($something['ElementID'] == $value)
{
unset($available);
}
foreach($somethings as $key3 => $singlesomething)
{
$singleprice = $singlesomething['Cost'];
}
$total += $something['Cost'];
}
Why will the above first method return nothing? I then use this variable which now has the data in a Div Data- (data-single-cost="'.$singleprice.'" ) which is then used to POST a form
$singleprice = $_POST['single-cost'];
Yet it returns 0 even with the second method successfully getting the value
any ideas what I'm doing wrong?
I guess its because somehow program goes into the if and you have unset available in it, so singleprice gots nothing.
Maybe you should get a Xdebug and try some step debug to see what happend.
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>";
}
}
}
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;
}
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;
}
I'm trying to filter an array, in which the filter function is supposed to check for multiple conditions. For example, if element x starts with a capital letter, the filter function should return true. Except, if the element before element x satisfies certain other conditions, then element x should not stay in the array and the filter function should therefore return false.
Problem is that the callback function in array_filter only passes the element's value and not its key... doing some magic with array_search will probably work, but I was just wondering whether I'm looking in the wrong place for this specific issue?
Sounds like a case for a good old foreach loop:
foreach ($arr as $k => $v) {
// filter
if (!$valid)
unset($arr[$k]);
}
$newArray=array();
foreach($oldArray as $key=>$value){
if(stuff){
$newArray[$key]=$value;
}
}
or
foreach($array as $key=>$value){
if(stuff){
unset($array[$key]);
}
}
Did you use simple foreach?
$prev;
$first = true;
$result = array();
foreach ($array as $key => $value)
{
if ($first)
{
$first = false;
// Check first letter. If successful, add it to $result
$prev = $value;
continue; // with this we are ignoring the code below and starting next loop.
}
// check $prev's first letter. if successful, use continue; to start next loop.
// the below code will be ignored.
// check first letter... if successful, add it to $result
}