I have two arrays in my code.
Need to perform a foreach loop on both of these arrays at one time. Is it possible to supply two arguments at the same time such as foreach($array1 as $data1 and $array2 as $data2)
or something else?
If they both the same keys, you can do this:
foreach($array1 as $key=>data1){
$data2 = $array2[$key];
}
Assuming both have the same number of elements
If they both are 0-indexed arrays:
foreach ($array_1 as $key => $data_1) {
$data_2 = $array_2[$key];
}
Otherwise:
$keys = array_combine(array_keys($array_1), array_keys($array_2));
foreach ($keys as $key_1 => $key_2) {
$data_1 = $array_1[$key_1];
$data_2 = $array_2[$key_2];
}
Dont use a foreach. use a For, and use the incremented index, eg. $i++ to access both arrays at once.
Are both arrays the same size always?
Then this will work:
$max =sizeof($array);
for($i = 0; $i < $max; $i++)
array[$i].attribute
array2[$i].attribute
If the arrays are different sizes, you may have to tweak your approach. Possibly use a while.
iterative methods:
http://php.net/manual/en/control-structures.while.php
http://php.net/manual/en/control-structures.for.php
http://php.net/manual/en/control-structures.do.while.php
use for or while loop e.g.
$i = 0;
while($i < count($ar1) && $i < count($ar2) ) // $i less than both length !
{
$ar1Item = $ar1[$i];
$ar2Item = $ar2[$i];
$i++;
}
No to my knowledge with foreach, but can be easily done with for:
<?php
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
for ($i=0;$cond1 || $cond2;$i++)
{
if ($cond1)
{
// work with $array1
}
if ($cond2)
{
// work with $array2
}
$cond1 = 0<count($array1);
$cond2 = 0<count($array2);
}
?>
Related
I'll let the code speak:
$params = array();
$qtyCount = count(array(1,2,3,4,5));
$qtyAr = array(6,7,8,9,10);
$i = 1;
while($i <= $qtyCount){
$params['quantity_'.$i] .= $qtyAr[$i];
$i++;
}
But when I do this, the last value is missing.
BTW: the values in the qtyCount and qtyAr are bugus... just for example.
I would opt for a simpler approach:
array_walk($qtyAr, function($item, $index) use (&$params) {
$key = sprintf("quantity_%u", $index);
$params[$key] = $item;
});
It appears that you are starting at the wrong index (1), $i should be = 0 as others have pointed out.
You're missing the last element because your unasssociated array starts with 0 and your loop starts with 1. This is why foreach works so much better because it iterates over ALL your elements.
$qtyAr = array(6,7,8,9,10);
$i = 1;
foreach($qtyAr as $val) {
$params['quantity_' . $i] = $val;
$i++;
}
There is the following array:
arr1 = array(array('xxx',3),array('yyy',2));
I need to transform it into the array arr2, where the number of occurrence of each entry is equal to the 2nd column value in array arr1. For instance, for the above given arr1, arr2 should be the following:
arr2 = array(array('xxx'),array('xxx'),array('xxx'),array('yyy'),array('yyy'));
I wrote the following code, but my question is: Is it possible to do the same in a simpler way?
for ($i=0; $i<count($arr1); $i++) {
for ($j=0; $j<$arr1[i][1]; $j++) {
$arr2[] = array($arr1[0]);
}
}
I think a foreach is simpler and easier to read.
$arr1 = array(array('xxx', 3), array('yyy', 2));
$arr2 = array();
foreach ($arr1 as $arr)
{
for ($i = 0; $i < $arr[1]; $i++)
{
$arr2[] = array($arr[0]);
}
}
foreach ($arr1 as $entry) {
$arr2[] = array_fill(0, $entry[1], array($entry[0]));
}
$arr2 = call_user_func_array('array_merge', $arr2);
I wouldn't use it though. It's much less readable.
How do I set my foreach loop to start looking at the last entry of the array then each loop will go backwards instead of forward?
Thank you.
You could just reverse the array:
$reverse = array_reverse($array, true); // true to preserve keys
foreach($reverse as $key => $value) { /* etc. */ }
Or if you're sure that the array contains only numeric keys, this is probably faster:
for($i = count($array) - 1; $i >= 0; $i--) {
/* etc. */
}
foreach(array_reverse($array, true) as $key=>$value)
The array_reverse function will reverse an array.
You could do this:
$values = array();
$max = count($values);
foreach($i = $max; $i > 0; $i--) {
$key = $values[$i];
// do something with the key
}
I would like to skip a number of iterations of a foreach loop.
I have this code;
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
$key = $skip;
}
echo $letter;
}
This code doesn't do the trick. But with it I can sort of explain what I want. I what to actually move the pointer of the next iteration. It thought that by modifying the value of the key to the one i want would be enough. I understand that a possible solution would be this.
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
continue;
}
echo $letter;
}
But that kinda still does the iteration step. I would like to completely jump over the iteration.
Thanks
See: array_slice
$myarray = array("a","b","c","d","e","f","g","h");
foreach(array_slice($myarray, 5) as $key => $letter){
echo $letter;
}
You could just use a for loop instead
EDIT:
for($i = $skip; $skip > 0, $i < count($myarray); $i++) {
// do some stuff
}
That's not really how foreach loops (and iteration in general) work.
You can either do the continue version (which works fine; if it's the first thing in the loop body, it's essentially the same), or you can construct a different array to iterate over that doesn't include the first elements, or you can use a regular for loop.
<?php
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
$index = 0 ;
foreach($myarray as $key => $letter){
if( ($index % $skip) == 0 ){
echo $letter;
}
$index++;
}
?>
$myarray = array("a","b","c","d","e","f","g","h");
foreach (new LimitIterator (new ArrayIterator ($myarray), 5) as $letter)
{
echo $letter;
}
foreach (array_slice($myarray, 5) as $key => $letter) {
[...]
}
You can call $array->next() for $skip times. There are cases when you cannot easily use a regular for loop: for example when iterating a DatePeriod object.
I have an array of objects in PHP. I need to select 8 of them at random. My initial thought was to use array_rand(array_flip($my_array), 8) but that doesn't work, because the objects can't act as keys for an array.
I know I could use shuffle, but I'm worried about performance as the array grows in size. Is that the best way, or is there a more efficient way?
$result = array();
foreach( array_rand($my_array, 8) as $k ) {
$result[] = $my_array[$k];
}
$array = array();
shuffle($array); // randomize order of array items
$newArray = array_slice($array, 0, 8);
Notice that shuffle() function gives parameter as a reference and makes the changes on it.
You could use array_rand to pick the keys randomly and a foreach to gather the objects:
$objects = array();
foreach (array_rand($my_array, 8) as $key) {
$objects[] = $my_array[$key];
}
What about?:
$count = count($my_array);
for ($i = 0; $i < 8; $i++) {
$x = rand(0, $count);
$my_array[$x];
}
I just found this in our code and was hoping to find a more readable solution:
$rand = array_intersect_key($all, array_flip(array_rand($all, $count)));
You can get multiple random elements from an array with this function:
function getRandomElements(array $array): array
{
$result = [];
$count = count($array);
for ($i = 0; $i < rand(0, $count); $i++) {
$result[] = rand(0, $count);
}
$result = array_unique($result);
sort($result);
return $result;
}