Remove elements from array using PHP

No comments
Hello friends, today i am going to tell you about how to remove elements from array using PHP. Although, this is not a complete tutorial but, is very tricky. To make this happen you will have use PHP unset() method and some more functions are available in PHP that can also help you. So, lets start here.

Deleting array element:
Using unset() method:
If you want to delete single array element then you will use unset() method. You can also delete multiple elements, by using unset method.
For example, i have an array $arr and i want to remove second element then i will write my code as below.
$arr = array(0 => "a", 1 => "b", 2 => "c");
unset($arr[1]); // array key 1 is second element.
and then output will be something like:
Array(
[0]=>a
[2]=>b
)
Note that unset method does not change array index.
Using array_splice() method:
If you are using array_splice() method the array keys will be re-indexed automatically. This is the major deference between array_splice and unset methods.
An example:
$arr = array(0 => "a", 1 => "b", 2 => "c");
array_splice($arr, 1, 1);
Output will be:

Array(
[0]=>a
[2]=>b
)

No comments :

Post a Comment