How to access N-th element of an array in PHP

后端 未结 3 903
误落风尘
误落风尘 2021-02-07 11:36

I\'m embarrassed to ask this and it\'s most likely a duplicate, but my google results are coming up short (im searching incorrectly I guess) and such a basic question is infuria

相关标签:
3条回答
  • 2021-02-07 12:19

    If you want to access every N-th element:

    $n = 3;
    foreach (array_keys($arr) as $i => $key) {
        if (($i+1) % $n) {
            continue;
        }
    
        $value = $arr[$key];
    }
    
    0 讨论(0)
  • 2021-02-07 12:25

    If your keys are numeric, then it works exactly the same:

    $arr = ['one', 'two', 'three']; // equivalent to [0 => 'one', 1 => 'two', 2 => 'three']
    echo $arr[1]; // two
    

    If your keys are not numeric or not continuously numeric, it gets a bit trickier:

    $arr = ['one', 'foo' => 'bar', 42 => 'baz'];
    

    If you know the key you want:

    echo $arr['foo']; // bar
    

    However, if you only know the offset, you could try this:

    $keys = array_keys($arr);
    echo $arr[$keys[1]];
    

    Or numerically reindex the array:

    $values = array_values($arr);
    echo $values[1];
    

    Or slice it:

    echo current(array_slice($arr, 1, 1));
    

    Most likely you want to be looping through the array anyway though, that's typically what you do with arrays of unknown content. If the content is unknown, then it seems odd that you're interested in one particular offset anyway.

    foreach ($arr as $key => $value) {
        echo "$key: $value", PHP_EOL;
    }
    
    0 讨论(0)
  • 2021-02-07 12:35

    If you want to access the nth element without knowing the index, you can use next() n times to reach the nth element.

    for($i = 0; $i<$n; $i++){
        $myVal = next();
    }
    echo $myVal;
    

    There are other ways to access a specific element, already mentioned by @deceze.

    0 讨论(0)
提交回复
热议问题