I am using three different arrays of the same length, they are filled with values during a foreach loop:
foreach(......)
{
$array1[]=value1;
$array2[]=value2;
$array3[]=value3;
}
Then these arrays must be echoed:
$i = 0;
while($i < count($array1))
{
echo $array1[i];
echo $array2[i];
echo $array3[i];
$i++;
}
Is there a more elegant way to this this, for example a foreach loop an a multidimensional array?
Assuming your arrays :
$a1 = [2,3,4];
$a2 = [6,7,8];
$a3 = [9,10,11];
array_walk($a1, function($v, $k) use($a2, $a3)
{
echo $v;
echo $a2[$k];
echo $a3[$k];
});
Or simply
foreach($a1 as $k => $v)
{
echo $v;
echo $a2[$k];
echo $a3[$k];
}
Note:
You should never placing a count in while condition,
because it will called for each iterations ! that is not optimized
while($i < count($array1))
should be replaced by
$count = count($array1);
while($i < $count)
You could make an object of it? Probably create an actual class but StdClass works.
foreach(...)
{
$obj = new StdClass();
$obj->value1 = $value1;
$obj->value2 = $value2;
$obj->value3 = $value3;
$array[] = $obj;
}
foreach($array as $obj)
{
echo $obj->value1;
echo $obj->value2;
echo $obj->value3;
}
Still not very elegant but no ugly while loop.
Related
How to reindex this array after unsetting the array:
echo "before deleting:<br>";
$countries[] = "Japan";
$countries[] = "Korea";
$countries[] = "china";
echo $a = count($countries);
echo "<br>";
for($i= 0;$i < $a; $i++)
{
echo "$countries[$i]<br>";
}
unset($countries[1]);
echo "<br>";
After unset function, the count shows 2 but the 2nd
country name china is not echoed with the loop below.
echo "<hr>After deleting:<br>";
echo $a = count($countries);
echo "<br>";
//below is my forloop
for($i=0;$i < $a; $i++)
{
echo "$countries[$i]<br>";
}
</code>
Use array_values() to reindex:
$countries = array_values($countries);
However just use a foreach() to iterate all values:
foreach($countries as $country) {
echo $country;
}
Instead of
for($i=0;$i < $a; $i++)
{
echo "$countries[$i]<br>";
}
Use
foreach ($countries as $country) {
echo $country . '<br>';
}
Foreach doesn't really care about array keys, so it'll loop through fine. If you really want to use a standard for loop, call this before: $countries = array_values($countries); and that'll effectively reset the keys of the array.
How can I implement the code:
$numberList3 = array();
for($i = 0; $i < 10; $i++)
{
$numberList3[$i] = $i;
}
print_r($numberList3);
Using a foreach loop as the no. of times the loop is going to execute is decided by the user at run time.
Any suggestion.?
Use array_fill maybe?
<?php
$n = 10;
$arr = array_fill(0,$n,0);
foreach($arr as $k => $v) {
$arr[$k] = $k;
}
print_r($arr);
Or, as suggested by #deceze, use range
<?php
$n = 10;
$arr = array();
foreach(range(0,$n-1) as $v) {
$arr[$v] = $v;
}
print_r($arr);
Or when the value is the same as the key, you can use just this:
<?php
$n = 10;
$arr = range(0,$n-1);
// no foreach needed
print_r($arr);
foreach() works for object and array not for a single value.
What you can do create an array or object from users input.
like:
$userInput = 10;
$forEachArray = array_fill(0, $userInput, 0);
$arrayToDisplay = array();
foreach($forEachArray as $key){
$arrayToDisplay[$key] = $key;
}
print_r($arrayToDisplay);
I've two A and B arrays, first one (A) is simple array where as the second one (B) is array of arrays. I want to find whether some element in A is equal to element in B. For doing this I'm currently doing nested loops which results in n^3 complexity. How can I improve upon this.
for ($i = 0; $i <= count($A); $i++) {
if (isset($A[$i])) {
foreach ($B as $items) {
foreach ($items as $item) {
if ($item['Column1'] == $A[$i]['Column1']) {
array_push(A, "result");
unset($A[$i]);
unset($items);
break;
}
}
}
}
}
array_walk_recursive($B, function($val) {
if (in_array($val, $A)) echo "$val is in the \$A array!";
});
Try this, array_seacrh() will remove your one foreach loop :
for ($i = 0; $i <= count($A); $i++) {
if (isset($A[$i])) {
foreach ($B as $items) {
$t = array_search($A[$i]['Column1'], $items);
array_push($A, "result");
unset($A[$i]);
unset($items[$t]);
}
}
}
when creating your arrays you can create a $lookup_A and $lookup_B arrays, where the keys are the values from the original $A and $B
Then you can do a simple loop on $lookup_A and check for if (isset($lookup_B[$lookup_A_key]))
Also in your example if(isset($A[$i])) is always true i think
I have an array of numbers. I can print all values using for each command in php. But what I want is, I don't want to print first value (ie, array[0]) and want to print all other values.
foreach($array as $k=>$val){
if($k){echo $val;}
}
for brevity, i did only exactly what was asked. The first index has a value of 0 which is falsy, so the value won't get echoed when tested in the if condition.
$cloneArray = $array;
array_shift($cloneArray); // will remove the first element of array
foreach($cloneArray as $key => $value){
echo $key." = ".$value;
}
this will also work if your array is in format of
array('key1' => 'value1', 'key2'=> 'value2', ...)
There are dozens..thousands of simple ways to do this. I'm going to list six:
$array = array(5, 6, 7, 8, 9);
foreach ($array as $index => $elem) {
if ($index == 0) {
continue;
}
echo $elem;
}
foreach($array as $index => $elem) {
if ($index != 0) {
echo $elem;
}
}
for ($x = 1; $x < count($array); $x++) {
echo $array[$x];
}
$keep = array_shift($array);
foreach ($array as $index => $elem) {
echo $elem;
}
array_unshift($array, $keep);
foreach (array_diff($array, array($array[0])) as $elem) {
echo $elem;
}
function print_not_zero($elem, $index) {
if ($index) {
echo $elem;
}
}
array_walk($array, 'print_not_zero');
I don't want to insult you, but as a developer you should think more critically for a moment and take the time to visualize the problem. Otherwise you might waste too much time on stackoverflow.
$i = 0
foreach($array as $single)
{
if ($i > 0)
echo $single;
$i++;
}
Although, unless you're using an associative array, a for cycle would be better perhaps.
$i=array(0,1,2,3);
foreach($i as $key=>$value)
{
if($key!='0')
echo $value;
}
Here's my array:
$array = array(1,2,3,4,5,6,7,8,9,10);
I want to iterate through the array 5 times, do something else, then resume iteration where I left off.
foreach ($array as $value) {
//do something until key 5
}
//do something else now
//resume...
foreach ($array as $value) {
//key should start at 6
}
How can I do this? Is there a way to achieve this with a foreach loop?
Update: I realized it would be silly to repeat the same code twice. The reason I was asking this is because I'm using a foreach loop to display table rows. I wanted to display the first five and hide the rest. So this is what I ended up with:
<?php
$counter = 1;
foreach ($array as $object): ?>
<?php if ($counter > 5): ?>
<tr style="display: none;">
<?php else: ?>
<tr>
<?php endif; ?>
<td><?php echo $object->name; ?></td>
</tr>
<?php $counter++; ?>
<?php endforeach; ?>
You need to use PHP's internal array pointer.
Something like:
$arr = range(0, 9);
for($i = 0; $i < 5; $i++) {
print current($arr);
next($arr);
}
//the pointer should be half way though the array here
something like this:
$counter = 0;
foreach ($array as $value)
{
if($counter == 5)
{
do something random;
$counter++;
continue;
}
//do something until key 5
$counter++;
}
Just curious, but wouldn't calling a function in the array to do what you need done achieve the same result?
Use two arrays:
$first_five = array_slice($array, 0, 5);
$remainder = array_slice($array, 5);
Is there a reason you need to do this with foreach, as opposed to just for?
you can use each() to resume iterating.
$a = array(1,2,3,4);
foreach ($a as $v) {
if ($v == 2) break;
}
while (list($k, $v) = each($a)) {
echo "$k = $v\n";
}
I think jspcal had the best answer so far. The only modification I made to his code was to use a do-while loop instead, so it would not skip the element where first loop breaks.
$arr = array(1,2,3,4);
// Prints 1 2
foreach($arr as $v)
{
if ($v == 3)
{
break;
}
echo "$v ";
}
// Prints 3 4
do
{
echo "$v ";
}
while( list($k, $v) = each($arr) );
(For the problem as stated I wouldn't recommend it but:) You can also use the NoRewindIterator.
$array = array(1,2,3,4,5,6,7,8,9,10);
$it = new NoRewindIterator(new ArrayIterator($array));
foreach($it as $x) {
echo $x;
if ($x > 4) {
break;
}
}
// $it->next();
echo 'taadaa';
foreach($it as $x) {
echo $x;
}
prints 12345taadaa5678910.
(Note the duplication of the element 5. Uncomment the $it->next() line to avoid that).
It's a little kloodgy, but it should work:
foreach($array as $key => $value)
{
$lastkey = $key;
// do things
if($key == 5) break;
}
// do other things
foreach($array as $key => $value)
{
if($key <= $lastkey) continue;
// do yet more things
}