w3resource

PHP Array Exercises : Delete an element from an array


4. Delete Element & Normalize Keys

$x = array(1, 2, 3, 4, 5);
Delete an element from the above array. After deleting the element, integer keys must be normalized.

Sample Solution:

PHP Code:

<?php
// Create an indexed array $x with elements 1, 2, 3, 4, 5
$x = array(1, 2, 3, 4, 5);

// Dump the variable $x to display its structure and values
var_dump($x);

// Unset the element with index 3 in the array $x
unset($x[3]);

// Reset the array indices after unset using array_values()
$x = array_values($x);

// Echo a newline character for better formatting
echo '';

// Dump the variable $x again after unset and array_values
var_dump($x);
?>

Output:

array(5) {                                                  
  [0]=>                                                     
  int(1)                                                    
  [1]=>                                                     
  int(2)                                                    
  [2]=>                                                     
  int(3)                                                    
  [3]=>                                                     
  int(4)                                                    
  [4]=>                                                     
  int(5)                                                    
}                                                           
array(4) {                                                  
  [0]=>                                                     
  int(1)                                                    
  [1]=>                                                     
  int(2)                                                    
  [2]=> 
  int(3)                                                    
  [3]=>                                                     
  int(5)                                                    
} 

Flowchart:

Flowchart: Delete an element from an array

For more Practice: Solve these Related Problems:

  • Write a PHP script that deletes a specified element from an indexed array and then reindexes the array ensuring sequential numeric keys.
  • Write a PHP function to remove an element by value from an array and normalize the keys using array_values().
  • Write a PHP program to drop a particular index from an array and then output the array with freshly normalized keys.
  • Write a PHP script to remove all occurrences of a given value from an array and reassign keys to maintain a continuous index sequence.

Go to:


PREV : Sorted Capitals from CEU Array.
NEXT : Get First Element from Associative Array.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.