Thursday, 16 October 2014

PHP: Get the first element of an array

I have an array:
array( 4 => 'apple', 7 => 'orange', 13 => 'plum' )
I would like to get the first element of this array. Expected result: string apple
Solution:
<?php
 $arr = array( 4 => 'apple', 7 => 'orange', 13 => 'plum' );
 array_shift(array_values($arr));
print_r(reset($arr)); //echoes "apple"

//another way
echo array_shift(array_slice($arr, 0, 1));

//other information

$first_value = reset($arr); // First Element's Value
$first_key = key($arr); // First Element's Key

// other solution will work for PHP 5.4+:
echo array_values($arr)[0]; ?>

0 comments:

Post a Comment