Php foreach element index

How to find the foreach index?

$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?

14 Answers 14

$key is the index of each $array element

definitely, this question isn’t very specific, i took it to mean the OP was largely unaware of the $key=>$value syntax

well this is actually right, but should not be the accepted answer, since key can be a string too. say you do $myarr[‘foo’] = ‘bar’; this method fails

@Bison you are right in the meaning that it does not fail. But it fails to comply the OP question. He is looking for numerical values like the n-th element.

Like @Toskan says, this should not be the accepted answer. I think it’s better to just create a variable outside the loop and count from there, increasing it with vatiable++; on each iteration. The traditional way, but has always worked.

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.

Читайте также:  Php double quotes encode

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.

This should be useful if you want to use a plain old PHP associative array to store data which is to be exposed via the Iterable interface (where you need to keep track of where you are in a loop).

+1 for the alternative, but a function call in every iteration is a little heavier than using preassigned variables (i.e. using the $key from $key=>$value ). However, I bet the lower performance is non-significant/perceptible in a simple loop.

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.

It’s important to note that this approach gives the current iteration of the loop, NOT the current index of the iterated array.

foreach ($lists as $key=>$value)

it is easy and clean code

These two loops are equivalent (bar the safety railings of course):

for ($i=0; $i foreach ($things as $i=>$thing)
for ($i=0; $i foreach ($things as $i=>$thing)

I use ++$key instead of $key++ to start from 1. Normally it starts from 0.

@foreach ($quiz->questions as $key => $question) 

Question: <<++$key>>

question>>

@endforeach

PHP arrays have internal pointers, so try this:

foreach($array as $key => $value)

Works okay for me (only very preliminarily tested though).

$key is the $index and current($array) is equal to $value. So both is not required, just use $index and $value.

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

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

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.

Источник

Php foreach element index

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (iterable_expression as $value) statement foreach (iterable_expression as $key => $value) statement

The first form traverses the iterable given by iterable_expression . On each iteration, the value of the current element is assigned to $value .

The second form will additionally assign the current element’s key to the $key variable on each iteration.

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key() .

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.

$arr = array( 1 , 2 , 3 , 4 );
foreach ( $arr as & $value ) $value = $value * 2 ;
>
// $arr is now array(2, 4, 6, 8)
unset( $value ); // break the reference with the last element
?>

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset() . Otherwise you will experience the following behavior:

// without an unset($value), $value is still a reference to the last item: $arr[3]

foreach ( $arr as $key => $value ) // $arr[3] will be updated with each value from $arr.
echo » < $key >=> < $value >» ;
print_r ( $arr );
>
// . until ultimately the second-to-last value is copied onto the last value

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

It is possible to iterate a constant array’s value by reference:

Note:

foreach does not support the ability to suppress error messages using @ .

Some more examples to demonstrate usage:

/* foreach example 1: value only */

foreach ( $a as $v ) echo «Current value of \$a: $v .\n» ;
>

/* foreach example 2: value (with its manual access notation printed for illustration) */

$i = 0 ; /* for illustrative purposes only */

foreach ( $a as $v ) echo «\$a[ $i ] => $v .\n» ;
$i ++;
>

/* foreach example 3: key and value */

$a = array(
«one» => 1 ,
«two» => 2 ,
«three» => 3 ,
«seventeen» => 17
);

foreach ( $a as $k => $v ) echo «\$a[ $k ] => $v .\n» ;
>

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a [ 0 ][ 0 ] = «a» ;
$a [ 0 ][ 1 ] = «b» ;
$a [ 1 ][ 0 ] = «y» ;
$a [ 1 ][ 1 ] = «z» ;

foreach ( $a as $v1 ) foreach ( $v1 as $v2 ) echo » $v2 \n» ;
>
>

/* foreach example 5: dynamic arrays */

foreach (array( 1 , 2 , 3 , 4 , 5 ) as $v ) echo » $v \n» ;
>
?>

Unpacking nested arrays with list()

It is possible to iterate over an array of arrays and unpack the nested array into loop variables by providing a list() as the value.

foreach ( $array as list( $a , $b )) // $a contains the first element of the nested array,
// and $b contains the second element.
echo «A: $a ; B: $b \n» ;
>
?>

The above example will output:

You can provide fewer elements in the list() than there are in the nested array, in which case the leftover array values will be ignored:

foreach ( $array as list( $a )) // Note that there is no $b here.
echo » $a \n» ;
>
?>

The above example will output:

A notice will be generated if there aren’t enough array elements to fill the list() :

foreach ( $array as list( $a , $b , $c )) echo «A: $a ; B: $b ; C: $c \n» ;
>
?>

The above example will output:

Notice: Undefined offset: 2 in example.php on line 7 A: 1; B: 2; C: Notice: Undefined offset: 2 in example.php on line 7 A: 3; B: 4; C:

Источник

How to Find the foreach Index with PHP

In this tutorial, we provide you with helpful methods to find the foreach index in PHP.

Below, you can find three options with proper examples.

Applying the key Variable

The key variable contains the index of every value inside the foreach loop. In PHP, the foreach loop is used like this:

 foreach ($arrayName as $value) < //code > ?>

The value variable contains the value of every element of the array. Here is an example:

 $array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; foreach ($array as $key => $value) < echo "The index is = " . $key . ", and value is = " . $value; echo "\n"; > ?>

Here, the key variable stores the index of the foreach loop. The variable value demonstrates the value of every element within the array.

The output will look as follows:

The index is = 0, and the value is = 1 The index is = 1, and the value is = 2 The index is = 2, and the value is = 3 The index is = 3, and the value is = 4 The index is = 4, and the value is = 5 The index is = 5, and the value is = 6 The index is = 6, and the value is = 7 The index is = 7, and the value is = 8 The index is = 8, and the value is = 9 The index is = 9, and the value is = 10

Applying the index Variable

The index variable is applied as an additional variable for demonstrating the index of the foreach loop in any iteration.

 // Declare an array $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $index = 0; foreach ($arr as $key => $val) < echo "The index is $index"; $index++; echo "\n"; > ?>

It is essential to consider that the index variable should initially be initialized with a value. Afterwards, it increments any time the loop iterates.

The output will look like this:

The index is 0 The index is 1 The index is 2 The index is 3 The index is 4 The index is 5 The index is 6 The index is 7 The index is 8 The index is 9

Applying the key and index Variables

Now, let’s see how using both the key and index variables will look like.

 // Declare an array $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $index = 0; foreach ($arr as $key => $value) < echo "The index is $index"; $index = $key + 1; echo "\n"; > ?>

In the example above, the value of the key variable is kept with an increment within the index variable. So, in this case, both the key and index variables are used for finding the index of foreach.

Describing the foreach Loop in PHP

In PHP, the foreach loop is applied for looping through a block of code for every element inside the array. It is essential to note that the foreach loop only operates on objects and arrays. Once you try to use it on a variable with a different data type, it will issue an error.

Источник

How to get Array index in foreach

I have a foreach loop in php to iterate an associative array. Within the loop, instead of increamenting a variable I want to get numeric index of current element. Is it possible.

$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450); foreach($arr as $person) < // want index here >
$arr = array('name'=>'My name','creditcard'=>'234343435355','ssn'=>1450); $counter =0; foreach($arr as $person) < // do a stuff $counter++; >

2 Answers 2

Use this syntax to foreach to access the key (as $index ) and the value (as $person )

foreach ($arr as $index => $person)

Why would you need a numeric index inside associative array? Associative array maps arbitrary values to arbitrary values, like in your example, strings to strings and numbers:

$assoc = [ 'name'=>'My name', 'creditcard'=>'234343435355', 'ssn'=>1450 ]; 

Numeric arrays map consecutive numbers to arbitrary values. In your example if we remove all string keys, numbering will be like this:

$numb = [ 0=>'My name', 1=>'234343435355', 2=>1450 ]; 

In PHP you don’t have to specify keys in this case, it generates them itself. Now, to get keys in foreach statement, you use the following form, like @MichaelBerkowski already shown you:

foreach ($arr as $index => $value) 

If you iterate over numbered array, $index will have number values. If you iterate over assoc array, it’ll have values of keys you specified.

Seriously, why I am even describing all that?! It’s common knowledge straight from the manual!

Now, if you have an associative array with some arbitrary keys and you must know numbered position of the values and you don’t care about keys, you can iterate over result of array_values on your array:

foreach (array_values($assoc) as $value) // etc 

But if you do care about keys, you have to use additional counter, like you shown yourself:

$counter = 0; foreach ($assoc as $key => $value) < // do stuff with $key and $value ++$counter; >

Or some screwed functional-style stuff with array_reduce , doesn’t matter.

Источник

Оцените статью