Set array pointer to a specific key or value in PHP

Josh Sherman
2 min read
Software Development 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!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles