how to read an complex array in PHP - php

How to read the array below. For example i would like to set the 'actual_cash' to some other value. PLease help I am new to PhP.

$Cashups[0]['actual_cash'] = 50.22;
To change the first instance of actual_cash.
$Cashups[1]['actual_cash'] = 100.22;
To chance the second instance, and so on.
To loop through this array, you can do something like:
foreach($Cashups as &$c)
{
$c['actual_cash']=500.00;
}
Which would change al the actual_cash instances to 500.00

You can use foreach to iterate array
foreach($Cashups as $key => $value)
{
$value['actual_cash']='newval';
}
if you have only two items in array you could also do this
$Cashups[0]['actual_cash']='someval';
$Cashups[1]['actual_cash']='someval';

foreach($Cashups as $item){
$item['actual_cash'] = $mynewvalue;
}

using for loop:
for($i = 0; $i < count($Cashups); $i++) {
$Cashups[$i]['actual_cash'] = $yourValue;
}
using foreach loop:
foreach($Cashups as &$c) {
$c['actual_cash'] = $yourValue;
}

Try something like this
foreach($Cashups as &$cashup){
// referencing $cashup to change it's value
$cashup = 'new value';
}

Related

PHP cant add new object keys in foreach loop

I want to create new object keys in foreach loop so I write:
$all_variants = $p->variants;
foreach ($all_variants as $a) {
$a->discount_price = $a->price;
$a->original_price = $a->price;
$a->button_text = 'BUY';
}
but this code wont create new keys (discount_price, original_price, button_text) ... $all_variants->discount_price is undefinded ....
Whats bad in my code?
You can use next trick for this
$all_variants = $p->variants;
foreach ($all_variants as &$a) {
$tmp = (array)$a;
$tmp['discount_price'] = $tmp['price'];
$tmp['original_price'] = $tmp['price'];
$tmp['button_text'] = 'BUY';
$a = (object)$tmp;
}
Here object converted to array modified and converted to object again
php code online test
This works for me:
foreach ($p->variants as $a) {
$a['discount_price'] = $a['price'];
$a['original_price'] = $a['price'];
$a->button_text = 'BUY';
$all_variants[] = $a;
}
You can modify the original array, but not the copy of the element you get in the loop...
foreach($p->variants as $i => $a) {
// $p->variants[ $i ] corresponds to $a
$p->variants[ $i ]['discount_price'] = $a['price'];
}

Updating an multi dimensional array in php

Hello I am trying to update an value in an multi dimensional array which was not working can any one tell me what is the issue in the below code.
<?php
$array_m= array();
array_push($array_m,array('md5'=>'a','count'=>1));
array_push($array_m,array('md5'=>'b','count'=>1));
foreach ($array_m as $key=>$val)
{
if($val['md5']=='a') {
$val['count'] =5;
break;
}
}
print_r($array_m);
foreach ($array_m as $key=>$val)
This just loops through the values, you can't update them. You need to use a reference, so you can update the array.
foreach ($array_m as $key=>&$val)
Note the &, that will make it a reference.
You have the $key so you can reference the array using that:
if($val['md5']=='a') {
$array_m[$key]['count'] = 5;
break;
}
You should Chnage your Code like following,
<?php
$array_m= array();
$array_m[] = array('md5'=>'a','count'=>1);
$array_m[] = array('md5'=>'b','count'=>1);
foreach ($array_m as $key=>$val)
{
if($val['md5']=='a') {
$val['count'] =5;
break;
}
}
print_r($array_m);
You can set the value of 5 like this:
$array_m[$key]['count'] = 5;

add key dynamically to a php array

I have got following array in php:
theArray('id':'123','akey':'a';
'id':'234','akey':'b';
'id':'567','akey':'c';)
I would like to dynamically add another key in a loop so that my array will look like:
theArray('id':'123','akey':'a', 'anotherkey':'1';
'id':'234','akey':'b'; 'anotherkey':'1';
'id':'567','akey':'c'; 'anotherkey':'1';)
The code I have written is the following:
foreach($theArray as $row)
{
$row['anotherkey'] = "1";
}
but it is not working. What am I doing wrong?
You're not actually storing your new value in $theArray, you're just assigning it to your temporary $row variable. What you want to do is this:
foreach($theArray as $key => $row) {
$theArray[$key]["anotherkey"] = "1";
}
Try with
foreach($theArray as &$row)
{
$row['anotherkey'] = "1";
}
foreach($theArray as $key => $row)
{
$theArray[$key]['anotherkey'] = "1";
}
is more robust

PHP add key while a foreach without using '&' (reference)

Suppose I am looping an array like this:
foreach($cursor as $obj) { ... }
and the values inside are as following:
$obj['name'] => "foo"
$obj['surname'] => "test"
is there a way to add another key and value inside it, directly from the foreach, without using '&'? Something like this:
foreach($cursor as $obj) { $obj['age'] = 24; }
but without using this:
foreach($cursor as &$obj) { $obj['age'] = 24; }
Thanks in advance.
foreach($cursor as $k => $obj) {
$cursor[$k]['age'] = 24; //or whatever else you want to change it to
}

in foreach, isLastItem() exists?

Using a regular for loop, it's possible to comapred the current index with the last to tell if I'm in the last iteration of the loop. Is there a similar thing when using foreach? I mean something like this.
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = islast(); //boolean true/false
}
If not, is there at least a way to know the current index of the current iteration like $iteration = 5, so I can manually compare it to the length of the $array?
The counter method is probably the easiest.
$i = count($array);
foreach($array as $item){
//do stuff
//then check if we're in the last iteration of the loop
$last_iteration = !(--$i); //boolean true/false
}
You can use a combination of SPL’s ArrayIterator and CachingIterator class to have a hasNext method:
$iter = new CachingIterator(new ArrayIterator($arr));
foreach ($iter as $value) {
$last_iteration = !$iter->hasNext();
}
Here are a few methods for this;
$items = ["Bhir", "Ekky", null, "Uych", "foo"=>"bar"];
$values = array_values($items);
// Bhir, Ekky, Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = isset($values[$i + 1]);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
foreach ($values as $i => $item) {
print("$item");
$next = array_key_exists($i + 1, $values);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$i = count($values);
foreach ($items as $item) {
print("$item");
$next = !!(--$i);
if ($next) {
print(", ");
}
}
// Bhir, Ekky, , Uych, bar
$items = new \CachingIterator(new \ArrayIterator($items));
foreach ($items as $item) {
print("$item");
$next = $items->hasNext();
if ($next) {
print(", ");
}
}
No, you need to have a counter and know the amount of items in the list. You can use end() to get the last item in an array and see if it matches the current value in your foreach.
If you know that the values of the array will always be unique, you can compare the current $item to end($array) to know if you're at the last item yet. Otherwise, no, you need a counter.
You can get the key and the value in foreach() like this:
foreach($array as $key=>$value) { ... }
Alternatively, you could do a count() of the array so you know how many items there are and have an incrementing counter so that you know when you've reached the last item.
end($array);
$lastKey = key($array);
foreach($array as $key => $value) {
if ($key === $lastKey) {
// do something endish
}
}
The valid() method says if the ArrayIterator object has more elements.
See:
$arr = array("Banana","Abacaxi","Abacate","Morango");
$iter = new ArrayIterator($arr);
while($iter->valid()){
echo $iter->key()." - ".$iter->current()."<br/>";
$iter->next();
}

Categories