I have the following array:
array(5) {
["destino"]=> string(11) "op_list_gen"
["id_terminal"]=> string(0) ""
["marca"]=> string(2) "--"
["tipo"]=> string(2) "--"
["lyr_content"]=> string(14) "aawaw"
}
How can I remove the values "--" and empty values from the array?
I have tried using a foreach and removing the elements found with unset but it´s not working.
foreach ($array as $key => $arra) {
if(array_key_exists('--', $array)){
unset($arra[$key]);
}
}
You can use array_filter
to solve this:
$arr = [
"destino" => "op_list_gen",
"id_terminal" => "",
"marca" => "--",
"tipo" => "--",
"lyr_content" => "aawaw"
];
$newArr = array_filter($arr, function($value) {
return !in_array($value, ['', '--']);
});
$array = [
"destino" => "op_list_gen",
"id_terminal" => "",
"marca" => "--",
"tipo" => "--",
"lyr_content" => "aawaw"
];
$new_array = array_filter($array, function($item){
if($item != '--' || $item != '')
return $item;
})
var_dump($new_array)
array_filter()
will take each entry and return it if it's not --
or ''
Use array_filter:
$original = [
'destino' => 'op_list_get',
'id_terminal' => '',
'marca' => '--',
'tipo' => '--',
'lyr_content' => 'aawaw',
];
// values you want to filter away
$disallowArray = ['', '--'];
$filteredResult = array_filter($original, function($val) use($disallowArray) {
// check that the value is not in our disallowArray
return \in_array($val, $disallowArray, true) === false;
});
Result:
Array
(
[destino] => op_list_get
[lyr_content] => aawaw
)
You could remove values by simply looping over the array, creating a new array in the process:
$myarray = array(
"destino" => "op_list_gen",
"id_terminal" => "",
"marca" => "--",
"tipo" => "--",
"lyr_content" => "aawaw",
}
$newarray = array();
foreach($myarray as $key => $value) {
if($value != "--" && $value != "") {
$newarray[$key] = $value;
}
}
Or, more elegantly, you could use the array_filter
function. It takes a callback function that, for each value, decides whether to include it. This also returns a new array:
$newarray = array_filter($myarray, function($elem) {
if($elem != "" && $elem != "--") return $elem;
});
Generic approach should look like that:
$filter = function(...$excluded) {
return function ($value) use ($excluded) {
return !in_array($value, $excluded);
};
};
$newArray = array_filter($array, $filter('', '--'));
This approach is reusable, because you don't need to hardcode values right insight your filtering function.
As all the other answers say, array_filter is a good way to go about that. However, this is returning a new array and doesn't actually modify the original array. If that's what you're looking for, this might be a different approach:
// Start infinite loop
while(true){
// Check for value in array
if (($key = array_search('--', $arr)) !== false || ($key = array_search('', $arr)) !== false) {
// Unset the key
unset($arr[$key]);
// Reset array keys
$arr = array_values($arr);
} else {
// No more matches found, break the loop
break;
}
}