How do I get the first element of an array in PHP?

PHP

Solution: in PHP there are basically three types arrays :
  • Indexed Array
  • Associative Array
  • Multidimensional Array
  • There are several ways to get the first element of an array in PHP. Some of the methods use a foreach loop, a reset function, array_slice, array_values, array_reverse, and many others.
    • Direct access to index 0:
      // PHP program to access the first
      // array element $array = array ( ' engineer' , 'for' , ' computer' ); echo $array [0]?>
      Exit:
      engineer 
    • Using a foreach loop:
      // PHP program to access the first
      // array element $array = array ( 33 = > 'engineer' , 36 = > 'for' , 42 = > ' computer'); foreach ( $array as $name ) { echo $name ; // break the loop after the first iteration break ; }
      ?>
      Exit:
      engineer 
    • Using the reset() function: Thereset() function is used to move the internal array pointer to the first element.
      // PHP program to access the first
      // array element $array = array ( 33 = > 'engineer' , 36 = > 'for' , 4 2 = > 'computer'); echo reset ( $array ); ?>
      Exit:
      engineer 
    • Using the array_slice() function:array_slice() returns the sequence of elements from the array specified in the offset and length parameters. Syntax: array array_slice (array $array, int $offset [, int $length = NULL [, bool $preserve_keys = FALSE]])
      // PHP program to access the first
      // array element $array = array ( 33 = > 'engineer' , 36 = > 'for' , 42 = > 'computer'); echo array_slice ( $array , 0, 1) [0]; ?>
      Exit:
      engineer 
    • Using the array_values ​​() function:this function returns all values ​​in an array. 
      Syntax:
      array array_values ​​(array $array)
      // PHP program to access the first
      // array element $array = array ( 33 = > 'engineer' , 36 = > 'for' , 42 = > 'computer'); echo array_values ​​ ( $array ) [0]; ?>
      Exit:
      engineer 
    • Using the array_pop() function:this function removesan element from the end of the array. 
      Syntax:
      mixed array_pop (array & amp; $array) By default, array_reverse() resets everything numeric array keys to start from zero, while alphabetic keys will remain unchanged unless the second preserve_keys parameter is specified as TRUE. 
      This method is not recommended because it can take unwanted time-consuming processing of large arrays to reverse them before getting the first value.


      // PHP program to access the first
      // array element $array = array ( 33 = > ' engineer' , 36 = > 'for' , 42 = > ' computer'); echo array_pop ( array_reverse ( $array )) ; ?>
      Exit:
      engineer 




    Get Solution for free from DataCamp guru