change initial array inside the foreach loop? - php

i want to have a foreach loop where the initial array is changed inside the loop.
eg.
$array = array('red', 'blue');
foreach($array as $key => $value) {
$array[] = 'white';
echo $value . '<br />';
}
in this loop the loop will print out red and blue although i add another element inside the loop.
is there any way to change the initial array inside the loop so new elements will be added and the foreach will use the new array whatever is changed?
i need this kind of logic for a specific task:
i will have a if statement that search for a link. if that link exists, it is added to the array. the link content will be fetched to be examined if it contains another link. if so, this link is added, and the content will be fetched, so on so forth.. when no link is further founded, the foreach loop will exit

I don't think this is possible with a foreach loop, at least the way you wrote it : doesn't seem to just be the way foreach works ; quoting the manual page of foreach :
Note: Unless the array is referenced, foreach operates on a copy
of the specified array and not the
array itself.
Edit : after thinking a bit about that note, it is actually possible, and here's the solution :
The note says "Unless the array is referenced" ; which means this portion of code should work :
$i = 0;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
}
Note the & before $value.
And it actually displays :
red
blue
white
white
white
white
Which means adding that & is actually the solution you were looking for, to modify the array from inside the foreach loop ;-)
Edit : and here is the solution I proposed before thinking about that note :
You could do that using a while loop, doing a bit more work "by hand" ; for instance :
$i = 0;
$array = array('red', 'blue');
$value = reset($array);
while ($value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
$value = next($array);
}
Will get you this output :
red
blue
white
white
white
white

What you need to do is move the assignment inside the for loop and check the length of the array every iteration.
$array = array('red', 'blue');
for($i = 0; $i < count($array); $i++)
{
$value = $array[$i];
array_push($array, 'white');
echo $value . '<br />';
}
Be careful, this will cause an infinite loop (white will be added to the end of the array at every loop).

Maybe you should use some other way, like:
$ar = array('blue', 'red');
while ($a = array_pop($ar) {
array_push($ar, 'white');
}
Or something like this...

You can access the array by using the $key
$array = array('red', 'blue');
foreach($array as $key => $value) {
$array[$key] = 'white';
}

In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by
reference. [source]
All you have to do to your old code is
precede $value with &
like so
$array = array('red', 'blue');
foreach($array as $key => &$value) {// <-- here
$array[] = 'white';
echo $value . '<br />';
}
A while loop would be a better solution.
while (list ($key, $value) = each ($array) ) {
$array[] = 'white';
echo $value . '<br />';
}
If you don't need the $key variable, as your example suggests then using $value = array_pop($array) instead if list ($key, $value) = each ($array) would be a less expensive option. see #enrico-carlesso's Answer Here
As your array is sequantial(numeric,indexed) and not associative then you could use a for loop instead.
for ($key = 0; $key < count($array); ++$key) {
$value = $array[$i];
$array[] = 'white';
echo $value . '<br />';
}
As a side note.
I don't understand why its &$value and not &array.
&$value would suggest you can only modify the current element within the loop.
&array would suggest you could modify all array elements within the loop, including adding/removing element.

Related

Finding the first, last and nth row in a foreach loop

I was wondering if PHP has a gracefull method to find the first, last and/or nth row in a foreach loop.
I could do it using a counter as follows:
$i = 0;
$last = count($array)-1;
foreach ($array as $key => $row) {
if ($i == 0) {
// First row
}
if ($i == $last) {
// Last row
}
$i++;
}
But somehow this feels like a bit of a dirty fix. Any solutions or suggestions?
Edit
As suggested in the comments I moved the count($array) outside the loop.
foreach ($array as $key => $row) {
$index = array_search($key, array_keys($array));
if ($index == 0) {
// First row
}
if ($index == count($array) - 1) {
// Last row
}
}
In php we have current and end function to get first and last value of array.
<?php
$transport = array('foot', 'bike', 'car', 'plane');
echo $first = current($transport); // 'foot';
echo $end = end($transport); // 'plane';
?>
Modified :
Easy way without using current or end or foreach loop:
$last = count($transport) - 1;
echo "First : $transport[0]";
echo "</br>";
echo "Last : $transport[$last]";
Using Arrays
For the first element in an array you can simply seek $array[0];. Depending on the array cursor you can also use current($array);
For the middle of an array you can use a combination of array_search() and array_keys().
For the end of an array you can use end($array); noting that this aslso moves the array cursor to the last element as well (as opposed to simply returning the value).
Using Iterators
However ArrayIterator's may also work well in your case:
The first element is available at ArrayIterator::current(); once constructed. (If you're halfway through the iterator you'll need to reset().)
For the n'th or a middle element you can use an undocumented Iterator::seek($index); method.
For the last element you can use a combination of seek() and count().
For example:
$array = array('frank' => 'one',
'susan' => 'two',
'ahmed' => 'three');
$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();
// First:
echo $iterator->current() . PHP_EOL;
// n'th: (taken from the documentation)
if($iterator->valid()){
$iterator->seek(1); // expected: two, output: two
echo $iterator->current() . PHP_EOL; // two
}
// last:
$iterator->seek(count($iterator)-1);
echo $iterator->current() . PHP_EOL;
$arr = ["A", "B", "C", "D", "E"];
reset($arr);
// Get First Value From Array
echo current($arr);
// Get Last Value From Array
echo end($arr);
Visit below link for details of above used functions.
reset() : http://php.net/manual/en/function.reset.php
current() : http://php.net/manual/en/function.current.php
end() : http://php.net/manual/en/function.end.php

Passing two variables into a 'foreach' loop

I need help regarding a foreach() loop. aCan I pass two variables into one foreach loop?
For example,
foreach($specs as $name, $material as $mat)
{
echo $name;
echo $mat;
}
Here, $specs and $material are nothing but an array in which I am storing some specification and material name and want to print them one by one. I am getting the following error after running:
Parse error: syntax error, unexpected ',', expecting ')' on foreach line.
In the Beginning, was the For Loop:
$n = sizeof($name);
for ($i=0; i < $n; $i++) {
echo $name[$i];
echo $mat[$i];
}
You can not have two arrays in a foreach loop like that, but you can use array_combine to combine an array and later just print it out:
$arraye = array_combine($name, $material);
foreach ($arraye as $k=> $a) {
echo $k. ' '. $a ;
}
Output:
first 112
second 332
But if any of the names don't have material then you must have an empty/null value in it, otherwise there is no way that you can sure which material belongs to which name. So I think you should have an array like:
$name = array('amy','john','morris','rahul');
$material = array('1w','4fr',null,'ff');
Now you can just
if (count($name) == count($material)) {
for ($i=0; $i < $count($name); $i++) {
echo $name[$i];
echo $material[$i];
}
Just FYI: If you want to have multiple arrays in foreach, you can use list:
foreach ($array as list($arr1, $arr2)) {...}
Though first you need to do this: $array = array($specs,$material)
<?php
$abc = array('first','second');
$add = array('112','332');
$array = array($abc,$add);
foreach ($array as list($arr1, $arr2)) {
echo $arr1;
echo $arr2;
}
The output will be:
first
second
112
332
And still I don't think it will serve your exact purpose, because it goes through the first array and then the second array.
You can use the MultipleIterator of SPL. It's a bit verbose for this simple use case, but works well with all edge cases:
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($specs));
$iterator->attachIterator(new ArrayIterator($material));
foreach ($iterator as $current) {
$name = $current[0];
$mat = $current[1];
}
The default settings of the iterator are that it stops as soon as one of the arrays has no more elements and that you can access the current elements with a numeric key, in the order that the iterators have been attached ($current[0] and $current[1]).
Examples for the different settings can be found in the constructor documentation.
This is one of the ways to do this:
foreach ($specs as $k => $name) {
assert(isset($material[$k]));
$mat = $material[$k];
}
If you have ['foo', 'bar'] and [2 => 'mat1', 3 => 'mat2'] then this approach won't work but you can use array_values to discard keys first.
Another apprach would be (which is very close to what you wanted, in fact):
while ((list($name) = each($specs)) && (list($mat) = each($material))) {
}
This will terminate when one of them ends and will work if they are not indexed the same. However, if they are supposed to be indexed the same then perhaps the solution above is better. Hard to say in general.
Do it using a for loop...
Check it below:
<?php
$specs = array('a', 'b', 'c', 'd');
$material = array('x', 'y', 'z');
$count = count($specs) > count($material) ? count($specs) : count($material);
for ($i=0;$i<$count;$i++ )
{
if (isset($specs[$i]))
echo $specs[$i];
if (isset($material[$i]))
echo $material[$i];
}
?>
OUTPUT
axbyczd
Simply use a for loop. And inside that loop, extract values of your array:
For (I=0 to 100) {
Echo array1[i];
Echo array2[i]
}

Reverse order of foreach list items

I would like to reverse the order of this code's list items. Basically it's a set of years going from oldest to recent and I am trying to reverse that output.
<?php
$j=1;
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>
Walking Backwards
If you're looking for a purely PHP solution, you can also simply count backwards through the list, access it front-to-back:
$accounts = Array(
'#jonathansampson',
'#f12devtools',
'#ieanswers'
);
$index = count($accounts);
while($index) {
echo sprintf("<li>%s</li>", $accounts[--$index]);
}
The above sets $index to the total number of elements, and then begins accessing them back-to-front, reducing the index value for the next iteration.
Reversing the Array
You could also leverage the array_reverse function to invert the values of your array, allowing you to access them in reverse order:
$accounts = Array(
'#jonathansampson',
'#f12devtools',
'#ieanswers'
);
foreach ( array_reverse($accounts) as $account ) {
echo sprintf("<li>%s</li>", $account);
}
Or you could use the array_reverse function.
array_reverse() does not alter the source array, but returns a new array. (See array_reverse().) So you either need to store the new array first or just use function within the declaration of your for loop.
<?php
$input = array('a', 'b', 'c');
foreach (array_reverse($input) as $value) {
echo $value."\n";
}
?>
The output will be:
c
b
a
So, to address to OP, the code becomes:
<?php
$j=1;
foreach ( array_reverse($skills_nav) as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
Lastly, I'm going to guess that the $j was either a counter used in an initial attempt to get a reverse walk of $skills_nav, or a way to count the $skills_nav array. If the former, it should be removed now that you have the correct solution. If the latter, it can be replaced, outside of the loop, with a $j = count($skills_nav).
If you don't mind destroying the array (or a temp copy of it) you can do:
$stack = array("orange", "banana", "apple", "raspberry");
while ($fruit = array_pop($stack)){
echo $fruit . "\n<br>";
}
produces:
raspberry
apple
banana
orange
I think this solution reads cleaner than fiddling with an index and you are less likely to introduce index handling mistakes, but the problem with it is that your code will likely take slightly longer to run if you have to create a temporary copy of the array first.
Fiddling with an index is likely to run faster, and it may also come in handy if you actually need to reference the index, as in:
$stack = array("orange", "banana", "apple", "raspberry");
$index = count($stack) - 1;
while($index > -1){
echo $stack[$index] ." is in position ". $index . "\n<br>";
$index--;
}
But as you can see, you have to be very careful with the index...
You can use usort function to create own sorting rules
Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:
$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
echo $fruits[$i] . '<br>';
}
If your array is populated through an SQL Query consider reversing the result in MySQL, ie :
SELECT * FROM model_input order by creation_date desc
If you do not have Boolean false values in your array, you could use next code based on internal pointer functions:
$array = ['banana', 'apple', 'pineapple', 'lemon'];
$value = end($array);
while ($value !== false) {
// In case you need a key
$key = key($array);
// Do something you need to
echo $key . ' => ' . $value . "\n";
// Move pointer
$value = prev($array);
}
This solution works for associative arrays with arbitrary keys and do not require altering existing or creating a new one.
<?php
$j=1;
array_reverse($skills_nav);
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>

Is it possible in PHP for an array to reference itself within its array elements?

I'm wondering if the elements of array can 'know' where they are inside of an array and reference that:
Something like...
$foo = array(
'This is position ' . $this->position,
'This is position ' . $this->position,
'This is position ' . $this->position,
),
foreach($foo as $item) {
echo $item . '\n';
}
//Results:
// This is position 0
// This is position 1
// This is position 2
They can't "reference themselves" per se, and certainly not via a $this->position as array elements are not necessarily objects. However, you should be tracking their position as a side-effect of iterating through the array:
// Sequential numeric keys:
for ($i = 0; $i < count($array); ++$i) { ... }
// Non-numeric or non-sequential keys:
foreach (array_keys($array) as $key) { ... }
foreach ($array as $key => $value) { ... }
// Slow and memory-intensive way (don't do this)
foreach ($array as $item) {
$position = array_search($item, $array);
}
No, PHP's arrays are plain data structures (not objects), without this kind of functionality.
You could track where in the array you are by using each() and keeping track of the keys, but the structure itself can't do it.
As you can see here: http://php.net/manual/en/control-structures.foreach.php
You can do:
foreach($foo as $key => $value) {
echo $key . '\n';
}
So you can acces the key via $key in that example

How to find the foreach index?

Is it possible to find the foreach index?
in a for loop as follows:
for ($i = 0; $i < 10; ++$i) {
echo $i . ' ';
}
$i will give you the index.
Do I have to use the for loop or is there some way to get the index in the foreach loop?
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
You can put a hack in your foreach, such as a field incremented on each run-through, which is exactly what the for loop gives you in a numerically-indexed array. Such a field would be a pseudo-index that needs manual management (increments, etc).
A foreach will give you your index in the form of your $key value, so such a hack shouldn't be necessary.
e.g., in a foreach
$index = 0;
foreach($data as $key=>$val) {
// Use $key as an index, or...
// ... manage the index this way..
echo "Index is $index\n";
$index++;
}
It should be noted that you can call key() on any array to find the current key its on. As you can guess current() will return the current value and next() will move the array's pointer to the next element.
Owen has a good answer. If you want just the key, and you are working with an array this might also be useful.
foreach(array_keys($array) as $key) {
// do stuff
}
You can create $i outside the loop and do $i++ at the bottom of the loop.
These two loops are equivalent (bar the safety railings of course):
for ($i=0; $i<count($things); $i++) { ... }
foreach ($things as $i=>$thing) { ... }
eg
for ($i=0; $i<count($things); $i++) {
echo "Thing ".$i." is ".$things[$i];
}
foreach ($things as $i=>$thing) {
echo "Thing ".$i." is ".$thing;
}
I think best option is like same:
foreach ($lists as $key=>$value) {
echo $key+1;
}
it is easy and normally
PHP arrays have internal pointers, so try this:
foreach($array as $key => $value){
$index = current($array);
}
Works okay for me (only very preliminarily tested though).
I use ++$key instead of $key++ to start from 1. Normally it starts from 0.
#foreach ($quiz->questions as $key => $question)
<h2> Question: {{++$key}}</h2>
<p>{{$question->question}}</p>
#endforeach
Output:
Question: 1
......
Question:2
.....
.
.
.
Jonathan is correct. PHP arrays act as a map table mapping keys to values. in some cases you can get an index if your array is defined, such as
$var = array(2,5);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
your output will be
2
5
in which case each element in the array has a knowable index, but if you then do something like the following
$var = array_push($var,10);
for ($i = 0; $i < count($var); $i++) {
echo $var[$i]."\n";
}
you get no output. This happens because arrays in PHP are not linear structures like they are in most languages. They are more like hash tables that may or may not have keys for all stored values. Hence foreach doesn't use indexes to crawl over them because they only have an index if the array is defined. If you need to have an index, make sure your arrays are fully defined before crawling over them, and use a for loop.
I solved this way, when I had to use the foreach index and value in the same context:
$array = array('a', 'b', 'c');
foreach ($array as $letter=>$index) {
echo $letter; //Here $letter content is the actual index
echo $array[$letter]; // echoes the array value
}//foreach
I normally do this when working with associative arrays:
foreach ($assoc_array as $key => $value) {
//do something
}
This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:
foreach ($array as $indx => $value) {
//do something
}
foreach(array_keys($array) as $key) {
// do stuff
}
I would like to add this, I used this in laravel to just index my table:
With $loop->index
I also preincrement it with ++$loop to start at 1
My Code:
#foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
#endforeach

Categories