Learn how to flatten a nested array in PHP with a simple and practical example. π In this video, you will discovered how to handle complex arrays and convert them into a single-level array. Perfect for beginners and anyone looking to sharpen their PHP skills.
This is an improved solution from https://dev.to/lavary/how-to-flatten-an-array-in-php-four-methods-dnd#:~:text=In%20the%20above%20code%2C%20we,current%20element%20as%20its%20argument
$data = [2, "Abigael", "Paul", 45.3, ["Paulina", "Trust", 23, 45], True, ["Address" => "12 New layout", "Balance" => 56000]];
function array_flatten($array) {
$output = [];
for ($t = 0; $t < count($array); $t++) {
if(!is_array($array[$t])) {
array_push($output, $array[$t]);
} elseif(is_array($array[$t])) {
foreach ($array[$t] as $key => $value) {
if (!is_numeric($key) & $key != 0) {
array_push($output, $value);
} else {
array_push($output, $value);
}
}
}
}
return($output);
}
echo "<p style='font-weight:bold;'>Final Method Our Method (Myself and my students - Christabel and Great)</p>";
$quick = array_flatten($data);
echo "Flatten array - " ;
print_r($quick);
echo "<p>Count - ".count($quick) ."</p>";
GitHub Repository
https://github.com/HamplusTech/flatten-PHP-complex-nested-array-/tree/main
YouTube Video
https://youtu.be/YAdh8g-JHK4
Top comments (0)