2

I have 2 arrays:

$array1 = array(1 => '12', 2 => '4', 3 => '54');
$array2 = array(1 => '12', 2 => '4', 3 => '54', 4 => '124');

How would I go about making $array2 have the same number of keys as $array1, and removing any at the end.

So, I would end up with:

$array2 = array(1 => '12', 2 => '4', 3 => '54');

Being aware that the first array may contain a different number of keys.

2 Answers 2

8

Use array_slice:

$array2 = array_slice($array2, 0, count($array1), true);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I tried to use array_slice, but I couldn't get it to work (I had the count as the second option, and no 0). Thanks! (I'll accept in 9 minutes).
-1

you can also yuse array_pop it removes the last element from the array

array_pop

2 Comments

That isn't of any use to me - I made need to remove more than one entry.
It's not as elegant but you can do it in a while: while( count( $array1) < count $array2 ) { array_pop( $array1); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.