I have this array:
<?php
$array = [
'0' => ['asset' => 'wadus'],
'1' => ['asset' => 'wadus2'],
'2' => ['asset' => ''],
];
?>
The var_dump
one with the array returns me:
array(3) {
[0] =>
array(1) {
'asset' =>
string(5) "wadus"
}
[1] =>
array(1) {
'asset' =>
string(6) "wadus2"
}
[2] =>
array(1) {
'asset' =>
string(0) ""
}
}
If I iterate with foreach
I can discriminate empty elements.
$clean_assets = [];
foreach ($array as $asset) {
if(!empty($asset['asset'])) {
$clean_assets[] = $asset['asset'];
}
}
The one var_dump
returns $clean_assets
me:
array(2) {
[0] =>
string(5) "wadus"
[1] =>
string(6) "wadus2"
}
If I use a closure:
$clean_assets = array_map(function($asset) {
if(!empty($asset['asset'])){
return $asset['asset'];
}
}, $array);
It returns me this:
array(3) {
[0] =>
array(1) {
'asset' =>
string(5) "wadus"
}
[1] =>
array(1) {
'asset' =>
string(6) "wadus2"
}
[2] =>
array(1) {
'asset' =>
string(0) ""
}
}
Does anyone know why the anonymous function has this behavior?
I really don't know how the second response can come out like this (applying the closure) since applying your methods to me appears as follows:
Searching a bit in the documentation of the function
array_map
I found the following:Therefore, from the previous paragraph it can be deduced that if you pass a single array as an argument, it will retain its structure.
I have done a second test to verify that this was true with a different condition:
With the corresponding answer:
Conclusion : By singleing
array
the closure and using the functionarray_map
, it will maintain the structure of the original array by padding only the values that match the condition and leaving the rest of the values NULL.I have an error in the approach, the function , if the callback
array_filter
is not passed to it, returns an array in which the empty elements are eliminated.Example #2 :
array_filter()
without callback :The result of the example would be:
Example source: PHP:
array_filter