Split PHP array into two arrays based on associate keys -



Split PHP array into two arrays based on associate keys -

how split associate array 2 arrays given keys maintain in first resultant array?

for instance...

//given: $myarray=array('a'=>123,'b'=>'abc','c'=>321,'d'=>'cba','e'=>111); $split=array('a','c'); //obtain elements who's keys in $split $newarray1=array('a'=>123,'c'=>321); //obtain elements who's keys not in $split $newarray2=array('b'=>'abc','d'=>'cba','e'=>111);

no frills:

$newarray1 = []; $newarray2 = []; foreach ($myarray $key => $value) { if (in_array($key, $split)) { $newarray1[$key] = $value; } else { $newarray2[$key] = $value; } }

frills:

$newarray1 = array_intersect_key($myarray, array_flip($split)); $newarray2 = array_diff_key($myarray, $newarray1);

see also: array_intersect_key() array_flip() array_diff_key()

php arrays

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -