How to Delete an Element from an Array in PHP

How to Delete an Element from an Array in PHP

In this post we will give you information about How to Delete an Element from an Array in PHP. Hear we will give you detail about How to Delete an Element from an Array in PHPAnd how to use it also give you demo for it if it is necessary.

Use the PHP unset() Function

If you want to delete an element from an array you can simply use the unset() function.

The following example shows how to delete an element from an associative array and numeric array.

<?php
$arr1 = array("a" => "Apple", "b" => "Ball", "c" => "Cat");
unset($arr1["b"]); 
// RESULT: array("a" => "Apple", "c" => "Cat")
 
$arr2 = array(1, 2, 3);
unset($arr2[1]);
// RESULT: array(0 => 1, 2 => 3)
?>

If you see the above example carefully you will find that the unset() function didn’t reindex the array after deleting the value from the numeric array (line no-8). To fix this you can use the array_splice() function. It takes three parameters: an array, offset (where to start), and length (number of elements to be removed). Let’s see how it actually works:

<?php
$arr = array(1, 2, 3);
array_splice($arr, 1, 1);
// RESULT: array(0 => 1, 1 => 3)
?>

 

Hope this code and post will helped you for implement How to Delete an Element from an Array in PHP. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US