How to find the foreach index? - php

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

Related

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]
}

Accessing PHP array passed through $_POST

I passed 2 arrays through $_POST and am trying to use the data in a php function. I am able to loop through each of the arrays using a foreach loop.
However, I need to loop through one of these arrays while accessing the other one in tandem (ie, on the first element in array1, I need to access the first element of array2)--so a nested foreach loop obviously doesn't help.
I have found that I cannot access the values by numerical index, however--except the first value of the array.
Any help would be greatly appreciated.
Here is the current snippet:
$count = 1;
foreach ($quantityArray as $quantity):
if($quantity < 1){
...
$order_to_item_idArray[$count]…..
}
if($quantity > 0){
...
$order_to_item_idArray[$count]…...
}
...
$count = $count + 1;
endforeach;
You will want to use something like this to achieve what you want:
$a as $key => $c
Here (as pseudo code):
$a = array('dsa','das','asf');
$b = array('aaa','eee','ggg');
foreach ($a as $key => $c)
{
echo $c . " - " .$b[$key];
}
For your code, the line would be:
foreach ($quantityArray as $key => $quantity)

Create multiple span based on array

I have an array that looks like this:
$elm = 'a,b,c';
I need the values of the array so I use explode to get to them:
$q = explode(",",$elm);
I then would like to echo every single item into a span, so I make an array:
$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}
$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}
$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}
And then finally I output like this:
echo "<ul>";
for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
echo "<li>";
echo "<span>".$arr[$i]."</span>";
echo "<span>".$arr2[$i]."</span>";
echo "<span>".$arr3[$i]."</span>";
echo "</li>";
}
echo "</ul>";
The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.
The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.
Use a nested foreach loop to store all the outertexts in an array:
foreach (explode(",", $elm) as $elem) {
foreach ($html->find($elem) as $a) {
$arr[$elem][] = $a->outertext;
}
}
$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.
Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:
echo "<ul>";
foreach ($arr as $sub) {
echo "<li>";
foreach ($sub as $span) {
echo "<span>".$span."</span>";
}
echo "</li>";
}
echo "</ul>";

foreach step 5 steps forward in an array

How can I step forward 5 steps when using foreach to output an arrays value? So In this the put will be 1, 5
$array = ("1","2","3","4","5","6","7","8","9");
foreach ($array as &$value) {
echo $value; //Where do I tell it to move 5 paces forward?
echo "<br/ >";
}
If a foreach loop cannot be used, I'm willing to use something else. I don't think "while" or "for" can be used here?
$array = array("1","2","3","4","5","6","7","8","9");
for($i=0; $i<count($array); $i+=5) {
echo $array[$i];
echo "<br/ >";
}
I would use a while loop. Just set an index outside of the loop, and add 5 to it on each iteration of the loop. When the index is larger than the length of the list, terminate the loop.
A more compact way to express these instructions is a for loop:
for ($i=0; $i<count($array); $i = $i+5)
If it is not numerically indexed
$count = -1;
foreach ($array as &$value) {
$count++;
if ($count%4 != 0) continue;
echo "$value".PHP_EOL;
}

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

Categories