Get the current array key inside foreach

后端 未结 3 1812
悲&欢浪女
悲&欢浪女 2021-02-10 23:01

Ok so, I am building something for my employer for them to input products, they have very specific requirements. I have a form with dynamically generated fields like so... (obvi

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-10 23:04

    According to the PHP documentation of key():

    The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.

    The documentation (and example) shows that you need to provide the actual array as parameter, where you are using the value.

    So use something like this:

    $yourArray = $_POST['attribute'];
    foreach ($yourArray as $attributes){
      echo key($yourArray).' '.$attributes.'
    '; }

    Even though you notice that are aware that you have a 'somewhat unorthodox method of coding in comparison to some', it would be much better to use the foreach-loop in this way:

    foreach ($_POST['attribute'] as $attributeKey => $attributes){
        echo $attributeKey.' '.$attributes.'
    '; }

    as the key() method seems a bit 'dodgy' to me (being dependent on internal pointers).

    Check out the foreach documentation for more information on this use.

提交回复
热议问题