Skip to main content

Retrieving Single Elements

This lesson shows how to get one element out of an array: by its position, by a condition, or at random. It also shows how to check whether an element exists at all.

When a lookup can fail, PHP answers with null. Reading an index that does not exist, such as $words[5] in an array of 5 elements, does not stop the program: it raises a warning (Undefined array key 5) and gives null.

The null coalescing operator ?? makes the same read safe and silent: $words[5] ?? "missing" looks up the index without any warning and falls back to "missing" when there is no element. This pair — null for "not there" and ?? for the fallback — is the running idiom of this page.

PHP 8.4 also added ready-made search functions: array_find(), array_any() and array_all(). They are used below next to classics like in_array() and count().


Retrieve by Position

Every element in a plain list has a position called an index. The first index is 0, so the last one is count($words) - 1.

To read an element by position, write the index inside square brackets: $words[3]. PHP does not count from the end — $words[-1] would look for a key -1 that does not exist. The last element is read with array_key_last().

For an index that may be out of range, ?? replaces a whole family of helper functions: $words[$i] ?? null is "element at, or null", and $words[$i] ?? fallback($i) is "element at, or else".

Element at a position

$words[3] reads the element at index 3. Since counting starts at 0, that is the fourth word.

Prompt
Make an array with the words one, two, three, four, five. Print the element at index 3 using square brackets.
Output: PHP script
Element at a position

First and last element

The first element is $words[0]. For the last one, array_key_last($words) returns the last key — here 4, because the array has 5 elements but the first index is 0. $words[-1] would not work: PHP has no negative indexes on arrays.

Prompt
Make an array with the words one, two, three, four, five. Print the first element with index 0, then the last element using array_key_last.
Output: PHP script
First and last element

Element at a position, or null

elementAt() answers with the element or with null. Index 1 exists, so the first call prints two. Index 5 does not: the helper gives null, no warning is raised, and ?? "missing" at the call site turns the null into the text missing.

Prompt
Write an elementAt helper that returns the element at an index, or null when the index does not exist, using the ?? operator. Call it on the words one, two, three, four, five with index 1 and with index 5, and print each result with "missing" as the ?? fallback at the call site.
Output: PHP script
Element at a position, or null

Element at a position, or a fallback

The fallback after ?? can be computed. fallback(5) receives the index and builds the message "The value for index 5 is undefined". ?? is lazy: the function only runs when the element is really missing.

Prompt
Make an array with the words one, two, three, four, five. Read index 5 with the ?? operator and a fallback function that receives the index and builds the text "The value for index 5 is undefined". Print the result.
Output: PHP script
Element at a position, or a fallback

Retrieve by Condition

Often you do not know the position. You know a condition instead: the first word longer than 3 letters, the last word that starts with "f". The condition is a function that takes one element and returns true or false.

Since PHP 8.4 this is a one-liner: array_find() returns the first element that passes the test — or null when nothing does. So "nothing matched" needs no special flag: it is just null, and ?? or a !== null check handles it.

There is no last-match function. Reverse the array first with array_reverse(): the first match in the reversed array is the last match in the original one.

First match

array_find() gives the first word with strlen($w) > 3. That word is three.

Prompt
Make an array with the words one, two, three, four, five. Use array_find to find the first word longer than 3 letters and print it.
Output: PHP script
First match

Last match

array_reverse($words) puts five first. array_find() then walks the reversed array and stops at the first word that starts with f — which is the last such word of the original array.

Prompt
Make an array with the words one, two, three, four, five. Reverse the array with array_reverse and use array_find with str_starts_with to print the last word that starts with "f".
Output: PHP script
Last match

First match, or null

No word is longer than 6 letters, so array_find() returns null and ?? "not found" prints the fallback. In the numbers array the first even number is 2, so the !== null check passes and 2 is printed.

Prompt
Take the words one, two, three, four, five and the numbers 1, 2, 3, 4. Search the words for one longer than 6 letters with array_find and print "not found" through the ?? operator when the result is null. Then find the first even number and print it after a !== null check.
Output: PHP script
First match, or null

Last match, or null

The reversed numbers start with 4, and 4 is even — the search hits at once. Had there been no even number, array_find() would have returned null and the if would have printed nothing.

Prompt
Take the numbers 1, 2, 3, 4. Find the last even number by running array_find over the reversed array, and print it only when the result is not null.
Output: PHP script
Last match, or null

Retrieve a Present Value

A PHP array can hold null to mark a value that is missing. When you only want the first real value, the condition is simply $v !== null.

array_find() with that test returns the first element that actually holds a value — or null itself when the whole array is only gaps, which again reads naturally with ??.

First value that is not null

The array starts with a gap: null. The test $v !== null skips it, and array_find() returns two, the first value that is really there.

Prompt
Make an array holding null, "two" and "three". Use array_find with the test that the value is not null and print the first value that really exists.
Output: PHP script
First value that is not null

Random Element

To pick a random element, pick a random index. mt_rand($min, $max) returns a whole number between the two bounds, both included, so mt_rand(0, count($numbers) - 1) is exactly a valid index.

mt_srand(42) starts the generator from a fixed seed. With the same seed the program picks the same element every time, which makes the output predictable — this example seeds only so that its result is reproducible. Leave out mt_srand() when you want a different result on each run.

Pick a random element

With seed 42 the generator picks index 2, so the program prints 3. Change the seed and a different number can come out.

Prompt
Make an array with the numbers 1, 2, 3, 4. Seed the random generator with mt_srand(42), pick a random index with mt_rand from 0 to count minus 1, and print the element at that index.
Output: PHP script
Pick a random element

Check Element Existence

To check whether a value is in an array, use in_array(). Always pass true as the third argument: it demands that type and value match, so the string "1" is not confused with the number 1.

PHP has no containsAll(). A small helper with array_all() (new in PHP 8.4) does the job: every wanted value must pass its own in_array() check.

An array is empty when count($x) === 0 and not empty when count($x) > 0. The shorter empty($x) also exists, but be careful: it is true for any falsy value — 0, "", null — not only for empty arrays, so the explicit count() comparison says exactly what you mean.

Contains one value

four is in the array, so the first check prints true. zero is not, so the second one prints false. The third argument true makes in_array() compare with ===.

Prompt
Make an array with the words one, two, three, four, five. Use in_array with strict comparison to check whether "four" is in the array and whether "zero" is in the array. Print both answers with json_encode.
Output: PHP script
Contains one value

Contains all values

Both four and one are in the array, so containsAll() returns true. zero is missing, so the second call returns false — array_all() stops at the first wanted value that fails.

Prompt
Write a containsAll helper that returns true only when every value of a second array is found in the first one, using array_all and strict in_array. Check the words one, two, three, four, five for four and one, then for one and zero. Print both answers with json_encode.
Output: PHP script
Contains all values

Empty or not empty

$empty has count 0, so count($empty) === 0 is true. $words has 5 elements, so count($words) > 0 is also true. json_encode() turns each boolean into the text true.

Prompt
Make an array with the words one, two, three, four, five and an empty array. Print whether the count of the empty array is 0, then whether the count of the words array is greater than 0, both with json_encode.
Output: PHP script
Empty or not empty