Arken Arken - 3 months ago 11
PHP Question

Move element from one array to another

I have this array:

$arr1 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2',
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
);


What I want to do is take the first 3 elements, remove them and create a new array with them.

So you would have this:

$arr1 = array(
'54' => 'sdfsdf2',
'53' => '2ssdf',
'62' => 'sfds'
);

$arr2 = array(
'76' => '1sdf',
'43' => 'sdf2',
'34' => 'sdf2'
);


How can I perform this action
Thanks

Answer

The following code should serve your purpose:

$arr1 = array(
 '76' => '1sdf',
 '43' => 'sdf2',
 '34' => 'sdf2',
 '54' => 'sdfsdf2',
 '53' => '2ssdf',
 '62' => 'sfds'
); // the first array
$arr2 = array(); // the second array
$num = 0; // a variable to count the number of iterations
foreach($arr1 as $key => $val){
  if(++$num > 3) break; // we don’t need more than three iterations
  $arr2[$key] = $val; // copy the key and value from the first array to the second
  unset($arr1[$key]); // remove the key and value from the first
}
print_r($arr1); // output the first array
print_r($arr2); // output the second array

The output will be:

Array
(
    [54] => sdfsdf2
    [53] => 2ssdf
    [62] => sfds
)
Array
(
    [76] => 1sdf
    [43] => sdf2
    [34] => sdf2
)

Demo