[Solved] Deleting an element from an array in PHP

Deleting multiple array elements

If you want to delete multiple value from array must be elements and don’t want to unset call unset() or \array_splice() multiple times you can use the functions \array_diff() and use or \array_diff_key() depending on whether you know the values or the keys of the elements which you want to delete.

Hello Engineer, How are you ?, I am back with Deleting a element from array in php and i hope this blog you are read and you successfully understand this blogging. i am happy with you.

There are different ways to delete an array element from php laravel, where some are more useful for some specific tasks than others.

If you know the values of the array elements which you want to delete, then you can use \array_diff(). As before with unset() it won’t change the keys of the array.

Solution 1: RIGHT

Code:

$array = [0 => "laravel", 1 => "php", 2 => "mysql"];
unset($array[1]);
          // ↑ Key specify you want to delete

Output:

[
    [0] => "laravel"
    [2] => "mysql"
]

Solution 2:

\array_splice() method:

If you are use \array_splice() the keys will automatically not manually deifine be reindexed, but the associative keys won’t change you — as opposed to \array_values(), which will you convert value all keys to numerical and alphabetic keys.

\array_splice() needs the offset, not the key, as the second parameter are you understand okay.

Code:

$array = [0 => "laravel", 1 => "php", 2 => "mysql"];
\array_splice($array, 1, 1);
                   // ↑ Offset which you want to delete

Output:

[
    [0] => "laravel"
    [1] => "mysql"
]

array_splice(), same as unset(), take care the array by reference from laratuto. You don’t assign to the return values of those functions back to on the array.

Solution 3:

It should be noted that unset() will keep indexes untouched in this, which is what you’d expect when using string indexes (array as new value), but can be exit surprising when dealing with integer indexing arrays:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=> 0
  [1]=> 1
  [3]=> 3
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
 /* array(3) {
  [0]=> 0
  [1]=> 1
  [2]=> 3
} */

Output:

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=> 0
  [1]=> 1
  [2]=> 3
} */

I hopw your query has been resolved Thank you……………..

Leave a Comment