$removed = array_splice(array, start [, length [, replacement ] ]);
We'll look at array_splice( )
using this array:
$subjects = array('physics', 'chem', 'math', 'bio', 'cs', 'drama', 'classics');
We can remove the math, bio,
and cs elements by telling array_splice(
) to start at position 2 and remove 3 elements:
$removed = array_splice($subjects, 2, 3);
// $removed is array('math', 'bio', 'cs')
// $subjects is array('physics', 'chem');
If you omit the length, array_splice( ) removes to
the end of the array:
$removed = array_splice($subjects, 2);
// $removed is array('math', 'bio', 'cs', 'drama', 'classics')
// $subjects is array('physics', 'chem');
If you simply want to delete the elements and you
don't care about their values, you
don't need to assign the results of
array_splice( ):
array_splice($subjects, 2);
// $subjects is array('physics', 'chem');
To insert elements where others were removed, use the fourth argument:
$new = array('law', 'business', 'IS');
array_splice($subjects, 4, 3, $new);
// $subjects is array('physics', 'chem', 'math', 'bio', 'law', 'business', 'IS')
The size of the replacement array doesn't have to be
the same as the number of elements you delete. The array grows or
shrinks as needed:
$new = array('law', 'business', 'IS');
array_splice($subjects, 2, 4, $new);
// $subjects is array('physics', 'chem', 'math', 'law', 'business', 'IS')
To get the effect of inserting new elements into the array, delete
zero elements:
$subjects = array('physics', 'chem', 'math');
$new = array('law', 'business');
array_splice($subjects, 2, 0, $new);
// $subjects is array('physics', 'chem', 'law', 'business', 'math')