Crazy
Crazy

Reputation: 867

How to split array into two different array based on value?

I have an array as shown below

array:2 [▼
  0 => array:2 [▼
    "id" => 0
    "item_code" => "abc001"
  ]
  1 => array:2 [▼
    "id" => 1
    "item_code" => "abc002"
  ]
]

How can i split it into new array when id = 0?

// $newArr to store id = 0
0 => array:2 [▼
   "id" => 0
   "item_code" => "abc001"
]
// $oldArr to store id != 0
1 => array:2 [▼
   "id" => 1
   "item_code" => "abc002"
]

I want to store every id = 0 into $newArr and id !=0 into $oldArr.

Upvotes: 3

Views: 4444

Answers (3)

Sohel0415
Sohel0415

Reputation: 9853

If your $array is a collection then try where()-

$new_array = $array->where('id','=',0);
$old_array = $array->where('id','!=',0);

If its a array then make it a collection first using collect()-

$array = collect($array);

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

You can use collection methods. First, wrap your array:

$collection = collect($array);

1. Use the where():

@foreach ($collection->where('id', 0) as $item)
    {{ $item['item_code'] }}
@endforeach

@foreach ($collection->where('id', '!=', 0) as $item)
    {{ $item['item_code'] }}
@endforeach

2. Use the partition():

list($idIsZero, $idIsNotZero) = $collection->partition(function ($i) {
    return $i['id'] === 0;
});

In the most cases you don't need to transform collection back to array, but if you need to, use ->toArray() on a collection.

Upvotes: 4

Gyandeep Sharma
Gyandeep Sharma

Reputation: 2327

INPUT

$array = array(
    array("id" => 0,"item_code" => "abc001"),
    array("id" => 1,"item_code" => "abc002")
);

SOLUTION

$oldArray = array();
$newArray = array();
foreach($array as $row){
    if($row['id']==0)$oldArray[] = $row;
    else $newArray[] = $row;
}
echo "New<pre>";print_r($newArray);echo "</pre>";
echo "Old<pre>";print_r($oldArray);echo "</pre>";

OUTPUT

New
Array
(
    [0] => Array
        (
            [id] => 1
            [item_code] => abc002
        )

)
Old
Array
(
    [0] => Array
        (
            [id] => 0
            [item_code] => abc001
        )

)

Upvotes: 2

Related Questions