Image created with Canva

Essential PHP Array Functions Revealed

Serghei Pogor
8 min readApr 20, 2024

--

Ever had to deal with lots of data in your code?

Before you start making your own fancy ways to handle it, did you know PHP has some ready-to-use tricks up its sleeve?

Yep, PHP has some cool built-in stuff called array helpers that can save you time and headaches.

Think about it like this: Say you need to do something with a bunch of numbers or words. Instead of spending ages writing complicated code from scratch, you can use these pre-made tools to get the job done quicker and easier.

In this article, we’re going to check out these handy helpers and see how they can make your life as a coder way simpler. No fancy jargon, just straightforward tips to help you work smarter, not harder.

So, if you’re ready to level up your PHP skills and make your code more efficient, stick around.

Let’s dive into the world of PHP array tricks together!

array_map()

Let’s kick things off with array_map(). This nifty function takes an array and a callback function, then applies that function to each element of the array, returning a new array with the modified values. It's perfect for when you need to perform the same operation on every element of an array without writing repetitive code. Check out this example:

// Say we have an array of names
$names = ["Alice", "Bob", "Charlie", "David"];

// We want to convert each name to uppercase
$uppercase_names = array_map(function($name) {
return strtoupper($name);
}, $names);

// $uppercase_names will now be ["ALICE", "BOB", "CHARLIE", "DAVID"]

Pretty cool, right? This function can save you a ton of time and make your code cleaner and more concise. 💡

array_filter()

Next up, we’ve got array_filter(). This handy function takes an array and a callback function, then filters out elements based on whether the callback function returns true or false.

It's perfect for when you need to selectively remove elements from an array based on certain criteria. Let's take a look:

// Say we have an array of products with their prices
$products = [
["name" => "Laptop", "price" => 1200],
["name" => "Smartphone", "price" => 800],
["name" => "Headphones", "price" => 150],
["name" => "Tablet", "price" => 500],
];

// We want to filter out products with a price higher than $1000
$affordable_products = array_filter($products, function($product) {
return $product["price"] <= 1000;
});

// $affordable_products will now only contain products with prices less than or equal to $1000

With array_filter(), you can easily weed out the elements you don't need and focus on what matters.

It's like having a personal assistant for your arrays! 🕵️‍♂️

array_keys()

Now, let’s switch gears and venture into the world of fitness tracking apps. Imagine a fitness enthusiast named Max using a PHP application to log his workouts and track his progress.

Max can use array_keys() to extract specific workout types from his training logs. Here's how it could work:

// Say we have an array representing Max's workout log
$workout_log = [
"Monday" => "Running",
"Tuesday" => "Cycling",
"Wednesday" => "Yoga",
"Thursday" => "Running",
"Friday" => "Weightlifting",
];

// We want to get the days when Max went running
$running_days = array_keys($workout_log, "Running");

// $running_days will now be ["Monday", "Thursday"]

With array_keys(), Max can analyze his training data and identify trends in his workout routine. It's like unlocking the secrets to optimizing his fitness regimen! 🏋️‍♂️

array_reduce()

If you’re a cryptocurrency enthusiast like many of us, keeping track of your Bitcoin transactions is crucial.

Whether you’re actively trading or simply holding, knowing your total Bitcoin holdings is essential. Luckily, PHP’s array_reduce() function can simplify this task.

Consider the following scenario:

// Array representing Bitcoin purchases with their amounts in BTC
$bitcoin_purchases = [0.1, 0.5, 0.3, 0.7, 1.2];

// Calculate the total amount of Bitcoin purchased
$total_bitcoin = array_reduce($bitcoin_purchases, function($total, $purchase) {
return $total + $purchase;
}, 0);

// $total_bitcoin will now be 2.8 BTC (0.1 + 0.5 + 0.3 + 0.7 + 1.2)

In this example, $bitcoin_purchases is an array containing the amounts of Bitcoin purchased in various transactions. We utilize array_reduce() to iterate over each transaction, accumulating the total Bitcoin holdings ($total) as we progress.

array_unique()

In the Mushroom Kingdom, Mario encounters various power-ups like mushrooms, fire flowers, and stars. However, sometimes he accidentally collects duplicate power-ups, which can clutter his inventory and hinder his progress.

Thankfully, array_unique() can help Mario tidy up his power-up collection:

// Array representing Mario's inventory with potential duplicate power-ups
$mario_inventory = [
"Mushroom",
"Fire Flower",
"Star",
"Mushroom",
"1-Up Mushroom",
];

// We want to remove duplicate power-ups from Mario's inventory
$unique_power_ups = array_unique($mario_inventory);

// $unique_power_ups will now contain only unique power-ups in Mario's inventory

With array_unique(), Mario can efficiently clean up his inventory, ensuring that each power-up serves a unique purpose and contributes to his success in saving Princess Peach.

count()

As developers, we often find ourselves working with cloud storage services like Google Drive to store and organize files. With the count() function, we can easily determine the number of files within a specific directory in Google Drive:

// Simulated array representing files in a Google Drive directory
$google_drive_files = [
"Document1.pdf",
"Document2.docx",
"Image1.jpg",
"Folder1" => [
"Subdocument1.pdf",
"Subdocument2.docx",
],
"Spreadsheet1.xlsx",
];

// We want to count the total number of files in the Google Drive directory
$total_files = count($google_drive_files);

// $total_files will now contain the total number of files in the directory

In this example, $google_drive_files represents an array structure mirroring the contents of a directory in Google Drive.

By applying the count() function, we can effortlessly determine the total number of files, including those nested within subdirectories.

in_array()

As avid gamers, we often find ourselves immersed in the diverse universe of Blizzard games, from epic adventures in World of Warcraft to intense battles in Overwatch. With the in_array() function, we can easily determine whether a specific game belongs to the illustrious Blizzard library:

// Array representing Blizzard games in our collection
$blizzard_games = [
"World of Warcraft",
"Overwatch",
"Diablo",
"StarCraft",
"Hearthstone",
];

// We want to check if "Diablo" is a Blizzard game
$is_diablo_blizzard_game = in_array("Diablo", $blizzard_games);

// $is_diablo_blizzard_game will now be true

In this example, $blizzard_games represents an array containing popular titles from Blizzard Entertainment. By utilizing the in_array() function, we effortlessly confirm whether "Diablo" is indeed part of the prestigious Blizzard portfolio.

array_walk()

In PHP, arrays are fundamental data structures for managing collections of data. array_walk() is a powerful function that enables us to traverse arrays and apply custom operations to each element efficiently.

// Array representing a list of names
$names = ["Alice", "Bob", "Charlie", "David"];

// Define a callback function to add emojis to each name
function add_emojis(&$value, $key) {
$value = "😊 " . $value . " 😎";
}

// Apply the add_emojis function to each element of the names array
array_walk($names, 'add_emojis');

// $names will now contain the names with emojis added to each

In this example, add_emojis() is a callback function that adds a happy face emoji before and a sunglasses emoji after each name in the array.

By passing this function to array_walk(), we apply the custom logic to each element of the $names array efficiently, adding a trendy twist to our data manipulation process.

array_chunk()

The array_chunk() function in PHP allows you to split an array into chunks of a specified size. This is particularly useful when dealing with large datasets, as it enables you to process data in more manageable portions.

// Array representing a list of trending hashtags
$trending_hashtags = ["#PHP", "#WebDevelopment", "#ArtificialIntelligence", "#Blockchain", "#Cryptocurrency", "#NFT"];

// Split the trending hashtags into chunks of 3 elements each
$hashtag_chunks = array_chunk($trending_hashtags, 3);

// $hashtag_chunks will now contain an array of arrays, each containing 3 trending hashtags

In this example, the $trending_hashtags array represents a list of trending topics on social media.

We use array_chunk() to split this array into chunks of 3 elements each, allowing us to process the trending hashtags in smaller batches.

This approach is beneficial for tasks such as displaying trending topics on a website or analyzing social media trends.

range()

The range() function in PHP generates a sequence of numbers or characters based on user-defined parameters. It provides flexibility in creating sequences with various options, making it a versatile tool for generating numeric or alphabetical ranges.

// Generating a sequence of numbers from 1 to 10
$numbers = range(1, 10);
// $numbers will contain [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Generating a sequence of even numbers from 2 to 10
$even_numbers = range(2, 10, 2);
// $even_numbers will contain [2, 4, 6, 8, 10]

// Generating a sequence of odd numbers from 1 to 9
$odd_numbers = range(1, 9, 2);
// $odd_numbers will contain [1, 3, 5, 7, 9]

// Generating a sequence of characters from 'a' to 'f'
$characters = range('a', 'f');
// $characters will contain ['a', 'b', 'c', 'd', 'e', 'f']

// Generating a sequence of uppercase characters from 'A' to 'F'
$uppercase_characters = range('A', 'F');
// $uppercase_characters will contain ['A', 'B', 'C', 'D', 'E', 'F']

// Generating a sequence of hexadecimal numbers from '00' to 'FF' with step 16
$hex_numbers = range('00', 'FF', 16);
// $hex_numbers will contain ['00', '10', '20', ..., 'F0']

In this example, we demonstrate the usage of range() with different options.

We generate sequences of numbers, characters, and hexadecimal values, showcasing its flexibility in creating various ranges.

This function is useful for tasks such as generating numeric ranges for loops, creating alphanumeric sequences for password generation, or constructing custom ranges for data processing.

list()

The list() function in PHP assigns variables as if they were an array.

It's a convenient way to extract values from arrays and assign them to variables in one step. list() can be particularly useful when working with arrays returned by functions or database queries.

// Example 1: Assigning variables from an array
$person = ["John", "Doe", 30];
list($firstName, $lastName, $age) = $person;
// $firstName will be "John", $lastName will be "Doe", and $age will be 30

// Example 2: Ignoring specific values
$coordinates = [10, 20, 30];
list($x, , $z) = $coordinates;
// $x will be 10, $z will be 30, and the second value is ignored

// Example 3: Assigning variables with keys in an associative array
$user = ["name" => "Alice", "age" => 25, "city" => "New York"];
list("name" => $userName, "age" => $userAge) = $user;
// $userName will be "Alice" and $userAge will be 25

// Example 4: Combining list() with array dereferencing
$data = [[1, 2], [3, 4]];
list($a, $b) = $data[0];
// $a will be 1 and $b will be 2

// Example 5: Using list() with function returns
function getCoordinates() {
return [100, 200, 300];
}
list($xCoord, $yCoord, $zCoord) = getCoordinates();
// $xCoord will be 100, $yCoord will be 200, and $zCoord will be 300

In these examples, we demonstrate different uses of the list() function.

It allows us to easily assign values from arrays to variables, including skipping specific values or using keys in associative arrays. list() provides a concise and readable way to extract and assign values from arrays, improving code clarity and reducing the need for intermediate variables.

And that’s it for today! We’ve had a fun time learning about some special tricks with PHP. These tricks are like magic tools that help make our coding adventures easier.

Using these tricks, we can save lots of time and make our code work better. It’s like having a special friend to help us out when we’re stuck.

So, the next time you’re working on your code and things get tricky, remember these special tricks we talked about today. They’ll help you solve problems faster and make coding more fun!

Keep practicing, keep smiling, and keep on coding! See you next time, friends!

🔔 Click Subscribe to catch more coding fun.
👏🏻 Love it? Give a big clap.
💬 Got a cool idea or funny coding joke? Drop it in the comments.

Share these tips with your fellow developers to help each other succeed together.

Thanks for hanging out and reading. You rock! 🚀

Hold on a sec!!! Want more of my fun stuff in your inbox? Sign up here! 📩

--

--