Question
I have the following PHP array:
$array = [
4 => 'apple',
7 => 'orange',
13 => 'plum',
];
I want to get the first element from this array, and I expect the result to be:
'apple'
A requirement is that the solution must not rely on passing the array by reference, so array_shift() is not suitable.
How can I get the first element of the array in PHP?
Short Answer
By the end of this page, you will understand how PHP arrays keep insertion order, how to read the first value safely, and which built-in functions are best when you want the first element without modifying the array.
Concept
PHP arrays are ordered maps. That means they store key-value pairs and also remember the order in which items were added.
In this example:
$array = [
4 => 'apple',
7 => 'orange',
13 => 'plum',
];
The first element is not the one with the smallest numeric key. It is the one that was inserted first, which is:
'apple'
This matters because PHP arrays are not simple zero-based lists only. They can have custom keys like 4, 7, and 13, and you often need the first inserted value rather than a value at index 0.
There are several ways to get the first element:
reset($array)moves PHP's internal array pointer to the first element and returns its valuearray_key_first($array)gets the first key, then you can read the value with that keyforeachcan read the first item without changing the array
Why this matters in real programming:
- You may need the first result from a query
- You may want a default item from a configuration array
- You may need the first error message or first record
- You may want to inspect data without removing or changing it
A key distinction is whether the method:
- modifies the array
- changes the internal pointer
- requires reference behavior
- works clearly with associative arrays
For this question, avoiding array_shift() is important because array_shift() removes the first element and reindexes numeric keys where applicable. That is often unnecessary if you only want to read the first value.
Mental Model
Think of a PHP array like a row of labeled boxes placed on a shelf.
- The labels might be
4,7, and13 - The first box placed on the shelf contains
'apple' - You want to look inside the first box without removing it
array_shift() is like taking the first box off the shelf and moving the rest.
reset() is like moving your finger back to the first box and reading its contents.
array_key_first() is like asking, "What is the label on the first box?" and then using that label to open it.
Syntax and Examples
Common ways to get the first element
1. Using reset()
$array = [
4 => 'apple',
7 => 'orange',
13 => 'plum',
];
$first = reset($array);
echo $first; // apple
reset() moves the internal pointer to the first element and returns its value.
2. Using array_key_first() in modern PHP
$array = [
4 => 'apple',
7 => 'orange',
13 => 'plum',
];
$firstKey = array_key_first($array);
$first = $firstKey !== null ? $array[$firstKey] : null;
echo $first; // apple
This is often the clearest option if you want the first value without changing the internal pointer.
3. Using foreach
$array = [
4 => 'apple',
7 => 'orange',
13 => 'plum',
];
$first = null;
foreach ($array as $value) {
$first = $value;
break;
}
echo $first; // apple
This works because foreach loops through the array in order, and break stops after the first item.
Best beginner choice
If you simply want the first value from an array and are okay with pointer movement:
$first = reset($array);
If you want a more explicit modern approach:
$firstKey = array_key_first($array);
$first = $firstKey !== null ? $array[$firstKey] : null;
Step by Step Execution
Consider this code:
$array = [
4 => 'apple',
7 => 'orange',
13 => 'plum',
];
$first = reset($array);
echo $first;
Step by step
-
PHP creates an array with three key-value pairs.
- Key
4=>'apple' - Key
7=>'orange' - Key
13=>'plum'
- Key
-
The array remembers insertion order.
- First inserted value:
'apple' - Second inserted value:
'orange' - Third inserted value:
'plum'
- First inserted value:
-
reset($array)does two things:- Moves the internal pointer to the first element
- Returns the first element's value
-
$firstnow contains:
'apple'
echo $first;prints:
apple
Empty array example
$array = [];
$first = reset($array);
var_dump($first);
Output:
bool(false)
This is important: reset() returns false for an empty array, so you must be careful if false could also be a valid array value.
Real World Use Cases
Where this is useful
Reading the first database result
$users = [
15 => 'Ava',
22 => 'Noah',
31 => 'Mia',
];
$firstUser = reset($users);
Getting the default configuration value
$themes = [
'default' => 'light',
'alt' => 'dark',
];
$firstTheme = reset($themes);
Showing the first validation error
$errors = [
'email' => 'Email is required',
'password' => 'Password is too short',
];
$firstError = reset($errors);
Picking the first API item
When an API response contains a list of records, you may want the first item for preview, fallback behavior, or testing.
$products = [
101 => 'Keyboard',
205 => 'Mouse',
];
$firstProduct = reset($products);
Real Codebase Usage
In real PHP projects, developers usually choose a method based on readability and side effects.
Common patterns
Guard clause for empty arrays
if (empty($array)) {
return null;
}
return reset($array);
This avoids problems when the array has no elements.
Using array_key_first() for clarity
$key = array_key_first($array);
return $key !== null ? $array[$key] : null;
This pattern is common when developers want to avoid pointer-related side effects.
First-item extraction after filtering
$activeUsers = array_filter($users, fn($user) => $user['active']);
$key = array_key_first($activeUsers);
$firstActiveUser = $key !== null ? $activeUsers[$key] : null;
Validation and error handling
$firstErrorKey = array_key_first($errors);
if ($firstErrorKey !== null) {
throw new Exception($errors[$firstErrorKey]);
}
Why developers avoid array_shift() here
- It removes the first element
- It may reindex numeric keys
- It is slower for large arrays when you only need to read
- It changes the original data structure
Common Mistakes
1. Assuming the first key is 0
Broken example:
$array = [4 => 'apple', 7 => 'orange', 13 => 'plum'];
echo $array[0];
This does not work because there is no key 0.
Fix
Use the first inserted element, not a guessed key:
echo reset($array);
2. Using array_shift() when you only want to read
Broken idea:
$first = array_shift($array);
This removes the first element from the array.
Fix
Use reset() or array_key_first() instead.
3. Forgetting that reset() affects the internal pointer
$array = ['apple', 'orange', 'plum'];
reset($array);
This is usually fine, but if other code depends on the current internal pointer, reset() changes it.
Fix
If pointer side effects matter, prefer:
$key = array_key_first($array);
$first = $key !== null ? $array[$key] : null;
4. Not handling empty arrays
Broken example:
$first = reset($array);
echo strtoupper($first);
If $array is empty, reset($array) returns false.
Fix
$first = reset($array);
if ($first !== false || !empty($array)) {
echo strtoupper($first);
}
Or use array_key_first().
5. Confusing first key with smallest key
$array = [10 => 'a', 2 => 'b', 1 => 'c'];
The first element is 'a', not 'c', because PHP uses insertion order here.
Comparisons
Comparing common approaches
| Approach | Returns first value | Modifies array | Changes pointer | Works with associative keys | Notes |
|---|---|---|---|---|---|
reset($array) | Yes | No | Yes | Yes | Simple and common |
array_key_first($array) + $array[$key] | Yes | No | No | Yes | Clear and modern |
foreach (...) { break; } | Yes | No | No | Yes | Verbose but reliable |
array_shift($array) | Yes | Yes | N/A | Yes | Removes first element |
reset() vs array_shift()
reset()reads the first valuearray_shift()removes the first value
reset() vs array_key_first()
reset()is shorterarray_key_first()is clearer when pointer changes are undesirablearray_key_first()makes empty-array checks more explicit
When to use which
- Use
reset()for quick access to the first value - Use
array_key_first()when you want clarity and no pointer side effects - Use
foreachwhen writing logic that naturally loops anyway
Cheat Sheet
// Get first value quickly
$first = reset($array);
// Get first value without changing internal pointer (PHP 7.3+)
$key = array_key_first($array);
$first = $key !== null ? $array[$key] : null;
// Get first value with foreach
$first = null;
foreach ($array as $value) {
$first = $value;
break;
}
Key rules
- PHP arrays preserve insertion order
- The first element is the first inserted item, not necessarily key
0 reset()returns the first value and moves the internal pointerarray_shift()removes the first element, so it is not ideal if you only want to readarray_key_first()returns the first key ornullfor an empty array
Empty array behavior
$array = [];
reset($array); // false
array_key_first($array); // null
Safe modern pattern
$key = array_key_first($array);
$first = $key !== null ? $array[$key] : null;
FAQ
How do I get the first element of an associative array in PHP?
Use reset($array) for the first value, or array_key_first($array) and then access $array[$key].
Does reset() remove the first element?
No. It only moves the internal pointer and returns the first value.
Why is array_shift() not a good choice here?
Because it removes the first element from the array and may reindex numeric keys.
What happens if the array is empty?
reset() returns false, while array_key_first() returns null.
Is the first element the same as the smallest key?
No. In PHP arrays, the first element is based on insertion order, not key size.
What is the best modern PHP way to get the first element?
If available, array_key_first() is a clear modern choice because it avoids internal pointer side effects.
Can I use $array[0] to get the first item?
Only if the array actually has a key 0. That is not true for associative arrays or arrays with custom numeric keys.
Mini Project
Description
Build a small PHP helper that returns the first value from an array without modifying the original array. This is useful in real applications when reading configuration, validation errors, or API results safely.
Goal
Create a reusable function that returns the first element of an array, or null if the array is empty.
Requirements
- Write a function that accepts an array as input.
- Return the first value without removing it from the array.
- Return
nullif the array is empty. - Demonstrate the function with both a non-empty array and an empty array.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.