Home » PHP: Get First Element Of Array With Examples

PHP: Get First Element Of Array With Examples

Last updated on December 24, 2020 by

Often, beginner PHP developers get stuck while working with an array. But we thank the rich PHP libraries & functions which provide an easy & convenient way to do the job. So in this post, we will see how to get the first element of an array in PHP by using inbuilt & user-defined functions

Get The First Element Of An Array In PHP

There are primarily three types of arrays in PHP:

  1. Indexed Array
  2. Associative Array
  3. Multidimensional Array

There are different methods available to get the first item of an array in PHP. We can use loops, array_shift(), array_pop(), reset(), array_slice(), array_values(), array_reverse(), etc.

01 Get First Item If You Know The Index or Key

1.1 Using Indexed Array

The indexed array is represented by an index number like 0,1,2, etc. PHP indexed array is also known as a numeric array. Let’s get the first element by taking a simple example below.

<?php 

$array = [ 'keyboard', 'mouse', 'laptop', 'scratchcode' ]; 

echo $array[0]; 

Output:

keyboard
1.2 Using Associative Array

The associative arrays are used to create key-value pairs. It is also similar to an indexed array, but the key difference is that it stores strings as an index instead of a number. This way, you can easily remember the index rather than an incremented number.

Let’s get the first element by taking a simple example of associative array below.

<?php 
/*@ Example of fruits stocks to get first element */
$array = [ 'apples' => 500, 'oranges' => 1000, 'bananas' => 200, 'cherries' => 5000 ]; 

echo $array['apples']; 

Output:

500
1.3 Multidimensional Array

If an array contain one or more array then it’s called Multidimensional array. Let’s see it with example

<?php

/*@ Example of fruits & vegetables stocks to get first element */
$array = [ 
            'fruits' => [ 'oranges', 'bananas', 'cherries' ],
            'vegetables' => [ 'potato', 'tomato' ] 
        ];
 
echo $array['fruits'][0]; /* get first parent's first child element */

print_r($array['fruits']); /* get first parent element */

Output:

oranges

Array
(
    [0] => oranges
    [1] => bananas
    [2] => cherries
)

02 Get First Item If You Don’t Know The Index or Key

There are some situations where you don’t know the exact index or key of the first element. In that case you can use the following ways to get the first item of an array. Let’s see them one by one.

2.1 Using current() function

The current() function is used to return the current element of an array. Every array has an internal pointer to its “current” element, which is initialized to the first element inserted into the array.

<?php 

/*@ Get the first element from PHP array */

$fruits = array( 
    77 => 'oranges',  
    25 => 'bananas',  
    'cherries' => 'cherries'
); 
  
echo current($fruits);

Output:

oranges
2.2 Using Loops

You can use any loop like for, while, foreach, etc to get the first element of an array but you need to break the loop after first iteration as shown below. But to get the first element loop isn’t a practical way so please considered other ways here.

<?php 

/*@ Get the first element from PHP array */

$fruits = array( 
    77 => 'oranges',  
    25 => 'bananas',  
    'cherries' => 'cherries'
); 
  
foreach ( $fruits as $fruit ) { 
    echo $fruit; 
  
    // break loop after first iteration 
    break;  
} 

Output:

oranges

Additionally, read our guide:

  1. How to Select Data Between Two Dates in MySQL
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. AJAX PHP Post Request With Example
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How to Convert Base64 to Image in PHP
  12. Check If A String Contains A Specific Word In PHP
  13. Dynamically Populate A Select Field’s Choices In ACF
  14. How To Find Duplicate Records in Database

That’s it from our end. We hope this article helped you to learn how to get first element of array with examples in PHP.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment