I have array with this structure:
$array = [
0=> ["field"=1, "value"="strawberry"]
1=> ["field"=2, "value"=null]
2=> ["field"=3, "value"="apple"]
]
How to iterate this $array
, so it's deletes objects where value==null
? After Iteration my array should look like:
$array = [
0=> ["field"=1, "value"="strawberry"]
1=> ["field"=3, "value"="apple"]
]
CodePudding user response:
You can utilise the array_filter()
to keep the array keys in-tact whilst removing null values. Using Arrow Functions in PHP 7.4^ you can try:
array_filter($array, fn($arr) => !is_null($arr['value']))
Output:
Array (
0 =>
array (
'field' => 1,
'value' => 'strawberry',
),
2 =>
array (
'field' => 3,
'value' => 'apple',
),
)
See it working over at 3v4l.org - OP said !is_null()
is required in the comment section and may need to be used.
If you want to reset the array keys you can use array_values()
.