Basic Array Operations | PHP
Published in
Mar 19, 2021
Insert
- Insert at the end. There are 2 ways to do this. I usually use the first.
$array[] = $value; // way 1
array_push($array, $value); // way 2
- Insert at the beginning
array_unshift($array , $value);
- Insert at specific position
$array_splice(
$array, // array that be inserted
$insert_index, // int
$remove_how_many_items_start_from_insert_index, // int
$inject_array, //[$value1, $value2...]
);
Delete
- Assign NULL doesn’t work
$array = [1, 2, 3, 4];
// Try to remove 3 for example
$array[2] = null;
// result: [1, 2, null, 4]
- Pop out the last item
array_pop($array);// [1,2,3,4] => [1,2,3]
- Unset
unset($array[$index])
Note! this way will leave the index empty, see below