How to remove element from array in PHP?

phperrorcode

PHP Error Code

Posted on July 21, 2022

How to remove element from array in PHP?

There are two ways to remove an element from the array in PHP.

  1. Unset() Method
  2. Array_splice() Method

Unset() Method

The unset() method is a built-in function in PHP that is used to remove or unset a single element from the array. Check out the syntax.

Example

<?php

  $arr = array("john","mark", "noah", "peter");
  unset($arr[2]);
  print_r($arr);

?>
Enter fullscreen mode Exit fullscreen mode

Output

Array (
[0] => jhon
[1] => mark
[3] => peter
)

Array_splice() Method

The array_splice function is used when you want to delete or remove or replace an element from the array.

Example

<?php

 $top = ["a"=> "AI", "b"=>"Programming", "c"=>"Python", 
 "d"=> "PHP"];
 array_splice($top, 2, 1);
 echo "<pre>";
 print_r($top);
 echo "</pre>";

?>
Enter fullscreen mode Exit fullscreen mode

Output

Array
(
[a] => AI
[b] => programming
[d] => php
)

Conclusion

In this tutorial, we discussed the two most helpful methods for removing an element from the array in PHP.

Suggested Articles

💖 💪 🙅 🚩
phperrorcode
PHP Error Code

Posted on July 21, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related