Get first and last element of PHP array
When writing code it is very common that you have to deal with collections of objects. It can be a set of customer names or the number of posts created by different users. Storing this data in an array helps us process the entire collection by iterating over it one by one.
PHP comes with two different types of arrays to help you store data. You can use a simple numeric array or create an associative array. Numeric arrays are useful when you just want to store a list of items, such as a list of customers. Associative arrays are useful when you want to store key-value pairs, such as a list of customer IDs and the total value of products purchased by each person.
From time to time, you must directly access elements in the array you created. In this quick tip, I'll show you how to get the first or last element of an array in PHP.
Get the first element of an array in PHP
Getting the first element of a simple numeric array is easy. Just get the element with index 0!
<?php $names = ["Adam", "Monty", "Sajal", "Andrew"]; // Output — Adam echo $names[0]; ?>
However, this does not work with associative arrays.
One of the most efficient ways to get the first element of a numeric or associative array in PHP is to use the reset()
function. This function sets the internal pointer of the array to its first element and returns the value of the first element. Here are some examples:
<?php $names = ['Andrew', 'Adam', 'Monty', 'James', 'Amanda', 'Jessica', 'Roy']; $country_capitals = ['Canada' => 'Ottawa', 'Germany' => 'Berlin', 'United States' => 'Washington D.C.', 'China' => 'Beijing', 'India' => 'New Delhi', 'Australia' => 'Canberra']; // Output — Andrew echo reset($names); // Output — Ottawa echo reset($country_capitals); ?>
As you can see, we don't need to know the key of the first element to get its value. All we have to do is pass the array to reset()
.
As I mentioned before, using reset()
will change the internal pointer of the array. If you want to get the first element in an array without changing it, you can use the array_key_first()
function. This will give you the first key of the array, which can be used to get the value of the first element.
<?php $names = ['Andrew', 'Adam', 'Monty', 'James', 'Amanda', 'Jessica', 'Roy']; $country_capitals = ['Canada' => 'Ottawa', 'Germany' => 'Berlin', 'United States' => 'Washington D.C.', 'China' => 'Beijing', 'India' => 'New Delhi', 'Australia' => 'Canberra']; // Output — Andrew echo $names[array_key_first($names)]; // Output — Ottawa echo $country_capitals[array_key_first($country_capitals)]; ?>
One thing you should remember is that array_key_first()
is only available starting with PHP 7.3.
Get the last element of an array in PHP
For simple numeric arrays, you can get the last element by calculating its index based on the array length.
<?php $names = ["Adam", "Monty", "Sajal", "Andrew"]; // Output — Andrew echo $names[count($names)-1]; ?>
But again, this doesn't work with associative arrays.
You can use the end()
function in PHP to get the last element of any PHP array. It sets the internal pointer to the last element of the array and returns its value. This makes it similar to the reset()
function we discussed in the previous section.
<?php $names = ['Andrew', 'Adam', 'Monty', 'James', 'Amanda', 'Jessica', 'Roy']; $country_capitals = ['Canada' => 'Ottawa', 'Germany' => 'Berlin', 'United States' => 'Washington D.C.', 'China' => 'Beijing', 'India' => 'New Delhi', 'Australia' => 'Canberra']; // Output — Roy echo end($names); // Output — Canberra echo end($country_capitals); ?>
Just like array_key_first()
, there is a corresponding array_key_last()
function which gives you the last key of the array without modifying it in any way. Once you have the key, you can easily access the last element of the array.
<?php $names = ['Andrew', 'Adam', 'Monty', 'James', 'Amanda', 'Jessica', 'Roy']; $country_capitals = ['Canada' => 'Ottawa', 'Germany' => 'Berlin', 'United States' => 'Washington D.C.', 'China' => 'Beijing', 'India' => 'New Delhi', 'Australia' => 'Canberra']; // Output — Roy echo $names[array_key_last($names)]; // Output — Canberra echo $country_capitals[array_key_last($country_capitals)]; ?>
Starting with PHP 7.3, the array_key_last()
function is also available.
Final Thoughts
There are also many ways to get the first or last array of elements in PHP. For example, you can use array_values()
and get the first or last element. However, if you don't need any extra information in the array, use reset()
, array_key_first()
, end()
and array_key_last( )
function will be more efficient.
The above is the detailed content of Get first and last element of PHP array. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.
