Table of Contents
Get the first element of an array in PHP
Get the last element of an array in PHP
Final Thoughts
Home Backend Development PHP Tutorial Get first and last element of PHP array

Get first and last element of PHP array

Sep 04, 2023 pm 07:05 PM
Extract first and last elements from php array Extract first and last elements of php array

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];

?>
Copy after login

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);

?>
Copy after login

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)];

?>
Copy after login

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];

?>
Copy after login

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);

?>
Copy after login

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)];

?>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

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

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

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

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

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

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

See all articles