Okay, so, let's say you have some data like this:
$things = [
0 => [ 'id' => 123, 'title' => '123 Title', 'content' => '123 Content' ],
1 => [ 'id' => 456, 'title' => '456 Title', 'content' => '456 Content' ],
2 => [ 'id' => 789, 'title' => '789 Title', 'content' => '789 Content' ],
];
Those numerical indexes aren't very useful. If id
is a unique key, it would be much more useful if it were indexed with the id
value as the array key.
So you just do:
$things = self::reindex_by_array_key( $things, 'id' );
And now you have:
$things = [
123 => [ 'id' => 123, 'title' => '123 Title', 'content' => '123 Content' ],
456 => [ 'id' => 456, 'title' => '456 Title', 'content' => '456 Content' ],
789 => [ 'id' => 789, 'title' => '789 Title', 'content' => '789 Content' ],
];
And now you can do isset( $things[$id_to_test] ) )
to see if an item with a given id
exists in the array.
This code was written for PHP 7.0+.
I was using wp_list_pluck()
until Lionel told me about array_column()
.
What other handy helpers do you use?
Lionel found a way to do this with a PHP core function! It's PHP 5.5+ and I somehow haven't heard of it until now.