0

I would like to get the index of the current element of an array in a loop. If I have this exemple :

<?php
  $array = array('a', 'b', 'c', 'd', 'e');
  foreach($array as $elem)
  {
    echo $elem;
  }
>

How could I get the index of elem in this loop (ex: 1 for 'b') ? I tried current($array) but the return value stay at 0 in my loop but with print_r() I have this.

print_r($array);
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )

Have you got any idea ?

Baptiste Gavalda
  • 197
  • 2
  • 16

3 Answers3

0

Try this;

foreach ($array as $key => $value) {
  echo $key;                              //<- for testing

  if($value==mayval)echo "The key is $key";
}
KOUSIK MANDAL
  • 2,002
  • 1
  • 21
  • 46
0

Use foreach ($array as $k => $v)

<?php
$array = array('a', 'b', 'c', 'd', 'e');
foreach($array as $k => $v) {
  echo $k . ' => ' . $v . PHP_EOL;
}

Output:

0 => a
1 => b
2 => c
3 => d
4 => e

https://eval.in/772092

alistaircol
  • 1,433
  • 12
  • 22
0

if you want all keys in an array, you can use array_keys() function.

If you want to check a key does exist in your array or not, use array_key_exists() function like: array_key_exists ( $key , $array );

or you simply want to access your keys, use foreach() like:

foreach($array as $key => $value){
    echo 'Key = '.$key.' , Value = '.$value;
}
Bhaskar Jain
  • 1,651
  • 1
  • 12
  • 20