Home » PHP » PHP Examples

PHP | Delete an element from an array using unset() function

Deleting an element from an array: Here, we are going to learn how to delete an element from an array in PHP using the unset() function?
Submitted by Bhanu Sharma, on August 10, 2019

Given an array and we have to remove an element from the array.

unset() function

To remove an element from an array, we can use a PHP library unset() function, it accepts the index and removes the element exists on the specified index.

We are also using another function var_dump() – which dumps the variable details i.e. here, it will print the array variable.

PHP code to remove an element from an array

<?php
//PHP code to remove an element from an array 

//declaring an array of strings
$array = array('the','quick','brown','fox');

//printing the array variable
var_dump($array);

//removing element from 1st index
unset ($array[1]);

//again, printing the array variable
var_dump($array);

//assigning the array after removing its element
//from 1st index to the new array
$array_new=array_values($array);

//printing the new array variable
var_dump($array_new);
?>

Output

array(4) {
  [0]=>
  string(3) "the"
  [1]=>
  string(5) "quick"  
  [2]=>
  string(5) "brown"  
  [3]=>
  string(3) "fox" 
}
array(3) {
  [0]=>
  string(3) "the" 
  [2]=>
  string(5) "brown"  
  [3]=>
  string(3) "fox" 
}
array(3) {
  [0]=>
  string(3) "the" 
  [1]=>
  string(5) "brown"  
  [2]=>
  string(3) "fox" 
}

Explanation:

Here, We've created an array ($array) and then used the PHP unset() method to remove index 1 (which is the 2nd value since array starts from 0). Once that's removed, we print the array using var_dump but there is a problem that the indexes haven't updated. So, we create $array_new by using array_values() method on the existing $array.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.