Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unset array in foreach php

i have data array this :

Array
(
    [0] => Array
        (
            [id] => 0
            [id_barang] => 0
        )

    [1] => Array
        (
            [id] => 231
            [id_barang] => 18572679-2.2.2.3
        )
)

here I am looping an array, and I want to delete the array which has id = 0

previously I created two foreach , the first to hold the array data , the second foreach to truncate the array if there is id = 0 , the question is can it be in 1 foreach ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this my code

            $arr = [];
            foreach($tampung as $key=>$value){ 
                $arr[] = $value;
            }

            foreach($arr as $key=>$rows){ // unset array id == 0
                if($rows['id'] == 0) 
                { 
                    unset($arr[$key]); 
                }   
            }

>Solution :

You can use array_filter to get a new array without id=0. For example:

<?php
$orig = [
    ['id'=>0, 'id_barang'=>'0'] ,
    ['id'=>213, 'id_barang'=>'18572679-2.2.2.3'],
    ['id'=>456, 'id_barang'=>'1879-2.2.2.3'],
    ['id'=>0, 'id_barang'=>'0'] ,
];

$new_array = array_filter($orig, function($entry) {return $entry['id'] !== 0;});
print_r($new_array); 

Output:

Array
(
    [1] => Array
        (
            [id] => 213
            [id_barang] => 18572679-2.2.2.3
        )

    [2] => Array
        (
            [id] => 456
            [id_barang] => 1879-2.2.2.3
        )

)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading