Question

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

Was it helpful?

Solution 2

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

OTHER TIPS

array_slice() will copy the first x elements of $arr1 into $arr2, and then you can use array_diff_assoc() to remove those items from $arr1. The second function will compare both keys and values to ensure that only the appropriate elements are removed.

$x    = 3;
$arr2 = array_slice($arr1, 0, $x, true);
$arr1 = array_diff_assoc($arr1, $arr2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top