0

i have some array

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => MOUSE
                    [2] => 0
                    [3] => 1
                  
                )

            [1] => Array
                (
                    [0] => 2
                    [1] => LAPTOP
                    [2] => 0
                    [3] => 0
                  
                )

            [3] => Array
                (
                    [0] => 4
                    [1] => PHONE
                    [2] => 0
                    [3] => 0
                    
                )
           
        )

)

i need to remove "0" values from the array so the result should be.

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => MOUSE
                    [2] => 0
                    [3] => 1
                )   
        )
)

how to remove it with a dynamic code ? because it will execute large of array. an i stuck in it for days

0

1 Answer 1

2

This filterArray function should work.

It just cheks the arrays inside the main array you submit (which in this case is $array["data"]), then checks the third position in each child array, and returns it if the value is not zero.

$array = array(
    "data" => array(
        array(
            "0" => 1,
            "1" => "MOUSE",
            "2" => 0,
            "3" => 1
        ),
        array(
            "0" => 2,
            "1" => "LAPTOP",
            "2" => 0,
            "3" => 0
        ),
        array(
            "0" => 4,
            "1" => "PHONE",
            "2" => 0,
            "3" => 0
        )
    )
);

function filterArray($elem) {
    if (is_array($elem)) {
        return (bool) $elem[3];
    }
    return false;
}
    
$array["data"] = array_filter($array["data"], "filterArray");

var_dump($array);

Here the output for your array:

array(1) {
    ["data"] => array(1) {
        [0] => array(4) {
            [0] => int(1)
            [1] => string(5) "MOUSE"
            [2] => int(0)
            [3] => int(1)
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

In this community the official language is English. Maybe you thought you were on Stack Overflow en Espanol. Could you translate your answer to English?
Oh, sorry. I will!
@Cmen then you have an error on your side, or your array structure isn't what you pasted here. This answer works fairly well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.