w3resource

PHP Array Exercises : Delete an element from an array

PHP Array: Exercise-4 with Solution

$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

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Create a PHP script which displays the capital and country name from the specified array $ceu. Sort the list by the name of the capital.
Next: Write a PHP script to get the first element of the specified array.

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.