John Davidson

php - Get the first element of an array

0 comments
Message:


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



One requirement: it cannot be done with passing by reference, so array_shift is not a good solution.



How can I do this?



My Answer:
array(4, 8, 15, 16, 23, 42);

To get the first element of the array, you can use the following code:

$firstElement = reset($array);

This code uses the reset() function to move the internal pointer of the array to the first element and returns that element.

Rate this post

3 of 5 based on 3861 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us