w3resource

PHP Array Exercises : Get the first element from an array


5. Get First Element from Associative Array

$color = array(4 => 'white', 6 => 'green', 11=> 'red');
Write a PHP script to get the first element of the above array.

Sample Solution:

PHP Code:

<?php
// Define an associative array with non-sequential keys
$color = array(4 => 'white', 6 => 'green', 11 => 'red');

// Output the value of the first element in the array using reset()
echo reset($color) . "\n";
?>

Output:

white

Flowchart:

Flowchart: Get the first element from an array

For more Practice: Solve these Related Problems:

  • Write a PHP script that retrieves the first element of an associative array regardless of the keys.
  • Write a PHP function to return the value of the first item in an associative array, using key resetting functions.
  • Write a PHP program to combine resetting the array pointer and then extracting the first element into a helper function.
  • Write a PHP script to demonstrate two different methods to obtain the first value of an associative array and compare their outputs.

Go to:


PREV : Delete Element & Normalize Keys.
NEXT : Decode JSON String.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.