imo, the easiest, most reliable and safest method of getting the value of the first row of a PHP array
is to use the current — Return the current element in an array function.
if (current($results)->meta_value === 'yes') {
//do something nice
}
Why?
The issue is that a PHP array is not a 'zero based linear list of cells in memory. It what is really an ordered hash map
in other languages.
It is able to use any string
as a key
or index
. If you don't use a key when you add an entry to the array then it uses a numeric index starting from zero.
The important point is that keys don't have to be sequential integers. They can be words (a string). i.e. There may be no zero index in the array
So, how to access the first element of a PHP array
if we don't know the indexes, which are keys
?
PHP Array Iterators
Every array
has an iterator
that is associated with it. The iterator points
to an element if the array has elements or is undefined for empty arrays.
When the array is created the iterator is always set to point to the first entry
Common Functions for accessing the Array Iterator
:
current - Return the element pointed to by the internal pointer
in an array
key - Fetch the current key from an array
- next - Advance the internal array pointer of an array
reset - Set the internal pointer of an array to its first element
Notes:
current
will return false
if not pointing at a valid element otherwise it will return the value.
Summary
By using the current
function to access an array you are certain to get the value of an entry whatever the index
or key
actually is.