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
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With