Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting an array without foreach

Tags:

php

I have an array of items

 $arr1 = Array(266=>"foo",178=>"bar",3="foobar");

and then I have an of array of numbers like this

 $arr2 = Array(0 => 266, 1 => 178);

and so what I want to do is split array one into two arrays

where the values of $arr2 that match the index of $arr1 are moved to a new array so I am left with

 $arr1 = Array(3="foobar");

 $arr2= Array(266=>"foo",178=>"bar");

that said I know I could do this with a foreach loop but I wonder if this is a simpler and faster way to do this

something like array_diff would be could but I don't think that will work

like image 631
mcgrailm Avatar asked Feb 28 '26 00:02

mcgrailm


1 Answers

Try:

$arr1 = array(266=>"foo",178=>"bar",3=>"foobar");
$arr2 = array(0 => 266, 1 => 178);

$tmp = array_diff_key ($arr1, array_flip($arr2));
$arr2 = array_diff($arr1,$tmp);
$arr1 = $tmp;
like image 158
Aaron W. Avatar answered Mar 01 '26 13:03

Aaron W.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!