PHP Array Functions Made Easy for Beginners

PHP Array Functions Made Easy for Beginners

👋 Hey there, PHP developer! If you’re just getting started with PHP, learning how to work with arrays is a game-changer. Arrays help you store, sort, and manage collections of data — like user names, product lists, or even API results. And to get the most out of them, you need to master the PHP array functions that make data handling a breeze.

In this guide, we’ll break down the most commonly used array functions in PHP, explain what they do in plain English, and show you how to use them with practical examples. Whether you’re coding your first website or diving into backend logic, these functions will save you time and headaches.

Let’s dive in to the essential and most used PHP array functions!

1. array_push() – Add Items to an Array

array_push() is used to add one or more elements to the end of an existing array. It’s like adding items to the end of a list.

🔧 Syntax:

PHP
array_push(array &$array, mixed ...$values): int

✅ Example:

PHP
$colors = ['red', 'green'];
array_push($colors, 'blue', 'yellow');
print_r($colors);

🧾 Output:

PHP
Array ( [0] => red [1] => green [2] => blue [3] => yellow )

2. array_pop() – Remove the Last Item

This function removes the last element of an array and returns it. It’s useful when you’re working with a stack-like structure (LIFO – Last In, First Out).

✅ Example:

PHP
$fruits = ['apple', 'banana', 'mango'];
$last = array_pop($fruits);
echo $last; // mango

After using array_pop(), the $fruits array will now contain apple and banana.

3. array_shift() – Remove the First Item

array_shift() removes the first element of an array and shifts the rest of the values down. This is often used in queue-like operations (FIFO – First In, First Out).

✅ Example:

PHP
$numbers = [10, 20, 30];
$first = array_shift($numbers);
echo $first; // 10

Now $numbers contains [20, 30].

4. array_unshift() – Add Items to the Beginning

Use this function to add one or more items to the beginning of an array, which shifts the other elements to higher indexes.

✅ Example:

PHP
$team = ['Mike', 'John'];
array_unshift($team, 'Anna');
print_r($team);

🧾 Output:

PHP
Array ( [0] => Anna [1] => Mike [2] => John )

Perfect for adding priority items.

5. in_array() – Check if a Value Exists

in_array() is a boolean function that checks if a specific value exists in an array. It returns true if found, false otherwise — great for validations.

✅ Example:

PHP
$roles = ['admin', 'editor', 'subscriber'];
if (in_array('admin', $roles)) {
    echo "Admin found!";
}

This is often used for user roles, permissions, etc.

6. array_keys() – Get All Keys from an Array

This function returns all the keys from an associative array. It’s handy when you only need the identifiers and not the values.

✅ Example:

PHP
$user = ['name' => 'Tom', 'age' => 30, 'email' => 'tom@example.com'];
$keys = array_keys($user);
print_r($keys);

🧾 Output:

PHP
Array ( [0] => name [1] => age [2] => email )

Useful when you’re looping over keys or debugging.

7. array_values() – Get All Values

array_values() gives you just the values of an array, without the keys. Perfect for numeric or value-based operations.

✅ Example:

PHP
$user = ['name' => 'Sara', 'age' => 25, 'email' => 'sara@example.com'];
$values = array_values($user);
print_r($values);

🧾 Output:

PHP
Array ( [0] => Sara [1] => 25 [2] => sara@example.com )

8. array_merge() – Merge Two or More Arrays

This function merges the elements of one or more arrays into one. If the arrays have the same string keys, later values overwrite the earlier ones.

✅ Example:

PHP
$first = ['a', 'b'];
$second = ['c', 'd'];
$combined = array_merge($first, $second);
print_r($combined);

🧾 Output:

PHP
Array ( [0] => a [1] => b [2] => c [3] => d )

Be careful: if you merge associative arrays with the same keys, the latter will overwrite the former.

9. array_slice() – Extract a Portion

array_slice() lets you grab a slice of an array based on an offset and length. It’s ideal for pagination or pulling a preview set.

✅ Example:

PHP
$letters = ['a', 'b', 'c', 'd', 'e'];
$slice = array_slice($letters, 1, 3);
print_r($slice);

🧾 Output:

PHP
Array ( [0] => b [1] => c [2] => d )

Great for pagination or previews.

10. array_filter() – Filter Items with a Callback

This function filters an array based on a callback function. Only values that return true will be included in the final array.

✅ Example:

PHP
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function($n) {
    return $n % 2 == 0;
});
print_r($even);

🧾 Output:

PHP
Array ( [1] => 2 [3] => 4 )

11. array_map() – Modify Each Element

array_map() allows you to apply a callback function to each element in the array, returning a new array with the transformed values.

✅ Example:

PHP
$nums = [1, 2, 3];
$squared = array_map(function($n) {
    return $n * $n;
}, $nums);
print_r($squared);

🧾 Output:

PHP
Array ( [0] => 1 [1] => 4 [2] => 9 )

This is perfect for transformations.

12. array_unique() – Remove Duplicate Values

This function filters out duplicate values and keeps only the first occurrence. It’s especially useful when working with tags, categories, or any user-generated input.

✅ Example:

PHP
$tags = ['php', 'html', 'php', 'css'];
$uniqueTags = array_unique($tags);
print_r($uniqueTags);

🧾 Output:

PHP
Array ( [0] => php [1] => html [3] => css )

Duplicates begone!

13. count() – Count Elements in an Array

Simple yet powerful. The count() function returns the number of elements in an array. You’ll use this often in loops, validations, and data checks.

✅ Example:

PHP
$items = ['pen', 'pencil', 'eraser'];
echo count($items); // 3

You’ll use this a lot — especially in loops and validations.

List of All PHP Array Functions:

FunctionDescription
array()Creates an array
array_change_key_case()Changes all keys in an array to lowercase or uppercase
array_chunk()Splits an array into chunks of arrays
array_column()Returns the values from a single column in the input array
array_combine()Creates an array by using the elements from one “keys” array and one “values” array
array_count_values()Counts all the values of an array
array_diff()Compare arrays, and returns the differences (compare values only)
array_diff_assoc()Compare arrays, and returns the differences (compare keys and values)
array_diff_key()Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc()Compare arrays, and returns the differences (compare keys and values, using user-defined function)
array_diff_ukey()Compare arrays, and returns the differences (compare keys only, using user-defined function)
array_fill()Fills an array with values
array_fill_keys()Fills an array with values, specifying keys
array_filter()Filters the values of an array using a callback function
array_flip()Flips/Exchanges all keys with their associated values in an array
array_intersect()Compare arrays, and returns the matches (compare values only)
array_intersect_assoc()Compare arrays and returns the matches (compare keys and values)
array_intersect_key()Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc()Compare arrays, and returns the matches (compare keys and values, using user-defined function)
array_intersect_ukey()Compare arrays, and returns the matches (compare keys only, using user-defined function)
array_key_exists()Checks if the specified key exists in the array
array_keys()Returns all the keys of an array
array_map()Sends each value of an array to a user-made function, which returns new values
array_merge()Merges one or more arrays into one array
array_merge_recursive()Merges one or more arrays into one array recursively
array_multisort()Sorts multiple or multi-dimensional arrays
array_pad()Inserts a specified number of items, with a specified value, to an array
array_pop()Deletes the last element of an array
array_product()Calculates the product of the values in an array
array_push()Inserts one or more elements to the end of an array
array_rand()Returns one or more random keys from an array
array_reduce()Returns an array as a string, using a user-defined function
array_replace()Replaces the values of the first array with the values from following arrays
array_replace_recursive()Replaces the values of the first array with the values from following arrays recursively
array_reverse()Returns an array in the reverse order
array_search()Searches an array for a given value and returns the key
array_shift()Removes the first element from an array, and returns the value of the removed element
array_slice()Returns selected parts of an array
array_splice()Removes and replaces specified elements of an array
array_sum()Returns the sum of the values in an array
array_udiff()Compare arrays, and returns the differences (compare values only, using user-defined function)
array_udiff_assoc()Compare arrays, and returns the differences (compare keys and values, using built-in and user-defined functions)
array_udiff_uassoc()Compare arrays, and returns the differences (compare keys and values, using two user-defined functions)
array_uintersect()Compare arrays, and returns the matches (compare values only, using a user-defined function)
array_uintersect_assoc()Compare arrays, and returns the matches (compare keys and values, using built-in and user-defined functions)
array_uintersect_uassoc()Compare arrays, and returns the matches (compare keys and values, using two user-defined functions)
array_unique()Removes duplicate values from an array
array_unshift()Adds one or more elements to the beginning of an array
array_values()Returns all the values of an array
array_walk()Applies a user function to every member of an array
array_walk_recursive()Applies a user function recursively to every member of an array
arsort()Sorts an associative array in descending order, according to the value
asort()Sorts an associative array in ascending order, according to the value
compact()Create array containing variables and their values
count()Returns the number of elements in an array
current()Returns the current element in an array
each()Deprecated from PHP 7.2. Returns the current key and value pair from an array
end()Sets the internal pointer of an array to its last element
extract()Imports variables into the current symbol table from an array
in_array()Checks if a specified value exists in an array
key()Fetches a key from an array
krsort()Sorts an associative array in descending order, according to the key
ksort()Sorts an associative array in ascending order, according to the key
list()Assigns variables as if they were an array
natcasesort()Sorts an array using a case insensitive “natural order” algorithm
natsort()Sorts an array using a “natural order” algorithm
next()Advance the internal array pointer of an array
pos()Alias of current()
prev()Rewinds the internal array pointer
range()Creates an array containing a range of elements
reset()Sets the internal pointer of an array to its first element
rsort()Sorts an indexed array in descending order
shuffle()Shuffles an array
sizeof()Alias of count()
sort()Sorts an indexed array in ascending order
uasort()Sorts an array by values using a user-defined comparison function and maintains index association
uksort()Sorts an array by keys using a user-defined comparison function
usort()Sorts an array by values using a user-defined comparison function

🎯 Final Thoughts

Mastering PHP array functions early in your programming journey will make your life a lot easier. These functions aren’t just convenient — they’re essential for writing clean, efficient, and readable code.

Take your time to play around with them, test different use cases, and try combining them to solve problems more effectively. Arrays are powerful, and once you get the hang of these tools, you’ll feel like a real PHP pro!

If you enjoyed this guide, consider bookmarking it for future reference or sharing it with your fellow learners. Keep coding — and have fun doing it!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *