php

How to get the first element of an array in PHP

In this tutorial, we are going to see how to get the first element of an array in PHP. If you already know the index or the exact key of an array, you can easily get the first element, as shown in the following example:
 

How to get the first element of an array in PHP
<?php
	// Example of an indexed array
	$languages = array("PHP", "Java", "Ada", "HTML", "CSS", "Fortran");
	echo $languages[0];
	 
	// Example of an associative array
	$languages = array("p" => "PHP", "j" => "Java", "a" => "Ada", "h" => "HTML");
	echo $languages["p"];
?>

Output:

PHP
PHP
 
However, in some cases you don’t know the exact index or key of the first item. In this case, you can use the array_values() function which returns an array of all the values of the array, as shown in the following example:

<?php
	$languages = array(5 => "PHP", 2 => "Java", 10 => "Ada", 1 => "HTML");
	echo array_values($languages)[0];
?>

Output:

PHP
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *