0

I need to access the first row of an array but not like this:

print_r($array[0]) ;

something like this and be built-in :

echo first($array) ;

is there anything like that in php?

6
  • 2
    reset() or even array_shift(). Commented Sep 15, 2013 at 10:30
  • What's wrong with using $array[0]? That is the proper syntax. Commented Sep 15, 2013 at 10:33
  • @MikeW array might be empty, so this might enforce E_NOTICE issue. Another walkaround is count($array) ? $array[0] : false. Commented Sep 15, 2013 at 10:34
  • $array[0] is not always present. How do you get the first element from array('randomstring'=>'value')? Commented Sep 15, 2013 at 10:36
  • 1
    how about list() construction ? list($a, $b, $c) = array(1,2,3); var_dump($a, $b, $c);. Commented Sep 15, 2013 at 10:42

2 Answers 2

2

reset($array) will move the internal array pointer to the first element and return that element as well.

Note that "the first element" not necessarily means the element with index 0. It means the first element that got added to the array:

$array[1] = "foo";
$array[0] = "bar";
$first = reset($array); // foo

You might want to sort the array before fetching the "first" element.

Sign up to request clarification or add additional context in comments.

Comments

2
$first_value_of_array = reset($array); // First Element's Value
$first_key_of_array = key($array); // First Element's Key

Hope this helps. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.