How to Compact an Array Without Using PHP Array Functions
When working with PHP, arrays play a vital role in managing data. Compacting an array refers to removing empty, null, or unwanted values from the array. While PHP offers built-in functions like array_filter, sometimes you may need to achieve this manually without using any built-in array functions.
Why Avoid PHP Array Functions?
- Learning Opportunity: Understanding how functions work internally.
- Restricted Environments: Situations where PHP functions are disabled or unavailable.
- Customization: Creating a tailor-made solution for unique requirements.
1. Understand the Problem
Suppose you have an array containing various types of values, including null, empty strings (“”), or zeros (0). Your goal is to remove these unwanted values.
Example
$array = [0, 1, "", 2, null, 3, "PHP", "", "Guide"];
2. Define a New Array for Cleaned Data
Start by creating an empty array to store valid values.
3. Iterate Over the Array
Use a foreach loop to go through each element. For each element, check if it meets the criteria for being “valid.”
4. Check Conditions
Manually verify whether the value is not null, not an empty string, and not zero (if zeros are also considered invalid).
5. Add Valid Values
If a value passes the conditions, add it to the new array.
Complete Code Example:
<?php
// Input array
$array = [0, 1, "", 2, null, 3, "PHP", "", "Guide"];
// Initialize an empty array
$compactArray = [];
// Iterate through the input array
foreach ($array as $value) {
// Check if the value is not null, not an empty string, and not zero
if ($value !== null && $value !== "" && $value !== 0) {
// Add valid value to the new array
$compactArray[] = $value;
}
}
// Output the compacted array
print_r($compactArray);
?>
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => PHP
[4] => Guide
)
- Manual Validation: You control the criteria for compacting the array.
- Performance: Efficient for small to medium-sized arrays.
- Flexibility: Easily adaptable to additional conditions.
Compacting an array without PHP functions is an excellent way to understand how arrays work at a deeper level. This approach is particularly useful for custom logic or restricted environments.
Keep Learning 🙂