4

How to Delete an Element from an Array in PHP

 2 years ago
source link: https://www.laravelcode.com/post/how-to-delete-an-element-from-an-array-in-php
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to Delete an Element from an Array in PHP

  1027 views

  1 year ago

PHP

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)
?>
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK