Set array pointer to a specific key or value in PHP

PHP arrays are absolutely fantastic. They hold stuff, doesn’t really matter
what. The interfacing is pretty consistent and there’s a boat load of built-in
array functions. What PHP lacks is the ability to set the array pointer to an
arbitrary key or value. There are ways to move forward and backward in the
array but not a dedicated function to set the internal pointer to a specific
key. Fortunately we can make it work, but it’s pretty archiac. We’ll need to
loop through the array and look for what we want.

$array = [
    'one'   => 'Uno',
    'two'   => 'Dos',
    'three' => 'Tres',
    'four'  => 'Cuatro',
    'five'  => 'Cinco',


// Just to be safe, let's ensure we're on the first element of the array
reset($array

// If we're looking for a specific key, we do this
while (!in_array(key($array), ['three', null])) {
    next($array
}

if (current($array) !== false) {
    // We found the key and set the pointer!
    var_dump(current($array
}

// Reset again so we have a clean pointer
reset($array

// If we're looking for a specific value, we do this
while (!in_array(current($array), ['Cinco', null])) {
    next($array
}

if (current($array) !== false) {
    // We found the value and set the pointer!
    var_dump(current($array
}

Like many things I post, this is more of an example than an actual use case. In
my experience, it’s pretty rate that you run into a scenario where you can
trust the structure of the array enough to want to set the pointer explicitly.
It’s usually must easier to assume that things are a mess and that checking if
a key exists is enough to suffice.

Have you ever had to hack together something like this? If so, comment below!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.