Issam Mousleh
Issam Mousleh

Reputation: 103

Delete empty value from array php

I have this array, and I need to delete the empty value and just keep the other values.

Array
(
    [12] => Array
        (
            [0] => 12
            [1] =>  Philippines
            [2] => 94,013,200
            [3] => Mid-2010
            [4] => 0.0136
        )
    [13] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
        )

Upvotes: 1

Views: 93

Answers (3)

Uttam Nath
Uttam Nath

Reputation: 672

You can use array_filter() and array_map() to remove all empty and null value or array by using this logic

Data:

The data contain empty value, null value, 0 value, or empty array element.

$records = [ 
    [
        2567317.0,"123123Z23",3752.0,"OOO qwasww","446691087", "M3F23O00431","860030362370389282",321229.63,"20230116","sdfsdf",2501217.0,0.0456
    ],
    [
        "","","","",""
    ],
    []
];

Logic:

The Logic is array_filler() function and array_map() function remove all unless element or array from data.

$data = array_filter(array_map(function ($record) {
    return array_filter(array_filter($record, function ($value) {
        return $value !== null || $value === 0.0 || $value === "0";
    }));
}, $records));

$data = array_filter($data);

print_r($data);

How work:

$value !== null || $value === 0.0 || $value === "0"

the logic keep 0,"0" elements and remove '' or null elements

$data = array_filter($data);

the logic remove empty arrays.

Upvotes: 0

devpro
devpro

Reputation: 16117

You can use array_map and array_filter functions for removing empty values from multi-dimensional array.

Solution:

$array = array_filter(array_map('array_filter', $yourArr));

Example:

$yourArr[12] = array('12','Philippines');
$yourArr[13] = array('','');
$array = array_filter(array_map('array_filter', $yourArr));

echo "<pre>";
print_r($array);

Result:

Array
(
    [12] => Array
        (
            [0] => 12
            [1] => Philippines
        )

)

Upvotes: 2

Pupil
Pupil

Reputation: 23958

Use array_map() and array_filter()

$result = array_map('array_filter', $a)

array_filter() removes blank elements from array in this case.

array_map() function calls a function on every array element, in this cause, it calls array_filter() and removes empty elements.

Working Code:

<?php
$a = array(12 => array(12, 'Philippines', '94,013,200', 'Mid-2010', '0.0136'), 13 => array('', '', '', '', ''));
$result = array_map('array_filter', $a);
echo "<pre>";
print_r($result);
echo "</pre>";
?>

Upvotes: 1

Related Questions