0

I have an SQL query that returns an array of objects called $results. The SQL query has a 'LIMIT 1', so there are never multiple instances of an object in the array (no need to loop). The array is below:

array(1) { [0]=> object(stdClass)#5875 (1) { ["meta_value"]=> string(3) "yes" } }

The meta_value object can either be 'yes or 'no'. I'd like to access 'meta_value' directly so I can use it's output in a condition, I'm struggling to find a method of doing this though. My code is below, this is not valid PHP however

if ($results->meta_value == 'yes') {
  //do something nice
}
Liam Fell
  • 1,308
  • 3
  • 21
  • 39

3 Answers3

3

Cause $results is array of objects you should select first element with index 0 and then take a certain property:

if ($results[0]->meta_value == 'yes') {}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

You could also use array_shift:

/* @var stdClass $result */
$result = array_shift($results);

if ($result->meta_value == 'yes') {
    //do something nice
}

For reference, see http://php.net/manual/en/function.array-shift.php.

localheinz
  • 9,179
  • 2
  • 33
  • 44
0

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:

  • currentwill 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.

Ryan Vincent
  • 4,483
  • 7
  • 22
  • 31