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
}
Related
here is what I'm trying to do. I'm retrieving information from a database via array. What is happening is the information from the previous array is going into the next array.
Here is the code:
$i = 0;
foreach ($array_name as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$array_name[$i]['new_infroamtion'] = $data'
}
}
So right now based on the code data from the table is correctly going into the first array, however, information based from the first array is going into the second array..
Let me know if you need anymore information.
Thank you
You are using $array_name while you are iterating through $array_name. This is valid code if you want to do this, but I don't think you do. You need to change the second $array_name to something else.
$i = 0;
foreach (**$array_name** as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id'] as $key => $test_id {
$data = ModelClass::Information($test_id);
**$array_name**[$i]['new_infroamtion'] = $data
}
}
I did find a solution. What I had to do was add the following
$s = array()
Then in the for loop, I added the following code:
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$s[] = $data
$array_name[$i]['new_infroamtion'] = $s'
}
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
function example()
{
foreach ($choices as $key => $choice) { # \__ both should run parallel
foreach ($vtitles as $keystwo => $vtitle) { # /
$options .= '<option value="'. check_plain($key) .'" title="' . $vtitle . '"' . $selected
.'>'. check_plain($choice) .'</option>';
} // end of vtitle
} // end of choice
return $options;
}
Answers to some of the below questions and what I am trying to achieve.
Array $choices is not numerically indexed.
Array $vtitle is numerically indexed.
They won't be shorter than each other as I have code which will take care of this before this code runs.
I am trying to return $options variable. The issue is that $choices[0] and $vtitle[0] should be used only once. Hope I was able to express my problem.
I do not want to go through the $vtitles array once for each value in $choices.
#hakre: thanks I have nearly solved it with your help.
I am getting an error for variable $vtitle:
InvalidArgumentException: Passed variable is not an array or object, using empty array
instead in ArrayIterator->__construct() (line 35 of /home/vishal/Dropbox/sites/chatter/sites
/all/themes/kt_vusers/template.php).
I am sure its an array this is the output using print_r
Array ( [0] => vishalkh [1] => newandold )
What might be going wrong ?
The below worked for me , thank you hakre
while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}
It does not work the way you outline with your pseudo code. However, the SPL offers a way to iterate multiple iterators at once. It's called MultipleIterator and you can attach as many iterators as you like:
$multi = new MultipleIterator();
$multi->attachIterator(new ArrayIterator($array1));
$multi->attachIterator(new ArrayIterator($array2));
foreach($multi as $value)
{
list($key1, $key2) = $multi->key();
list($value1, $value2) = $value;
}
See it in action: Demo
Edit: The first example shows a suggestion from the SPL. It has the benefit that it can deal with any kind of iterators, not only arrays. If you want to express something similar with arrays, you can achieve something similar with the classic while(list()=each()) loop, which allows more expressions than foreach.
while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}
Demo (the minimum number of elements are iterated)
See as well a related question: Multiple index variables in PHP foreach loop
you can't do it in foreach loop in general case. But you can do it like this in PHP5:
$obj1 = new ArrayObject($arr1);
$it1 = $obj1->getIterator();
$obj2 = new ArrayObject($arr2);
$it2 = $obj2->getIterator();
while( $it1->valid() && $it2->valid())
{
echo $it1->key() . "=" . $it1->current() . "\n";
$it1->next();
echo $it2->key() . "=" . $it2->current() . "\n";
$it2->next();
}
In older versions of PHP it will be like this:
while (($choice = current($choices)) && ($vtitle = current($vtitles))) {
$key_choice = key($choices);
$key_vtitle = key($vtitles);
next($choices);
next($vtitles);
}
Short Answer, no.
What you can do instead is:
foreach ($array1 as $k => $v)
performMyLogic($k, $v);
foreach ($array2 as $k => $v)
performMyLogic($k, $v);
If the keys are the same, you can do this:
foreach ($choices as $key => $choice) {
$vtitle = $vtitles[$key];
}
You may have to refigure your logic to do what you want. Any reason you can't just use 2 foreach loops? Or nest one inside the other?
EDIT: as others have pointed out, if PHP did support what you're trying to do, it wouldn't be safe at all.. so it's probably a good thing that it doesn't :)
Maybe you want this:
//get theirs keys
$keys_choices = array_keys($choices);
$keys_vtitles = array_keys($vtitles);
//the same size I guess
if (count($keys_choices) === count($keys_vtitles)) {
for ($i = 0;$i < count($keys_choices); $i++) {
//First array
$key_1 = $keys_choices[$i];
$value_1 = $choices[$keys_choices[$i]];
//second_array
$key_2 = $key_vtitles[$i];
$value_2 = $vtitles[$keys_vtitles[$i]];
//and you can operate
}
}
But this will work if size is the same. But you can change this code.
You need to use two foreach loops.
foreach ($choices as $keyChoice => $choice)
{
foreach ($vtitles as $keyVtitle => $vtitle)
{
//Code to work on values here
}
}
I got a site that executes the following code
$keywords = ($_SESSION[$_POST['ts']]);
print_r($keywords);
foreach ($keywords as $keyword) {
foreach ($keyword['whitelist'] as $entry) {
foreach ($_POST as $key => $value) {
if ($key == $entry['encoded_url']) {
$entry['ignore'] = $value;
$decodedURL = $this->base64->url_decode($entry['encoded_url']);
if ($value == 'noignore') {
echo "found!<br />";
$this->blacklist_model->remove($decodedURL);
$html = $this->analyse->getHTML($decodedURL);
$entry['html'] = $html[0];
$entry['loading_time'] = $html[1];
}
if($value == 'alwaysignore') {
$this->blacklist_model->add($decodedURL);
}
}
}
}
}
print_r($keywords);
The output looks like this:
http://pastebin.com/B3PtrqjB
So, as you see, there are several "found!"s in the output, so the if clause actually gets executed a few times and I expected the second array to contain new data like 'html', but, as you see, nothing changes. Is there anything to attend when changing values in multidimensional foreach() loops?
foreach creates a copy of the array and loops through that. Modifying values doesn't work.
You can get around this, though, by using references.
foreach ($keywords as &$keyword) {
foreach ($keyword['whitelist'] as &$entry) {
foreach ($_POST as $key => &$value) {
...
}
}
}
With that you can modify $value and it WILL affect the original array.
You suppose to change the Original array.
$entry is just an instance / unconnected node.
you need to change $keywords, and not its on the fly created nodes.
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';
}