How to remove an array element in a foreach loop?
Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable. The behavior of this function depends on different things. If the function is called from inside of any user defined function then it unsets the value associated with the variables inside it, leaving the value which is initialized outside it.
Syntax:
unset( $variable )
Return Value: This function does not returns any value.
Below examples use unset() function to remove an array element in foreach loop.
Example 1:
<?php // Declare an array and initialize it $Array = array( "GeeksForGeeks_1", "GeeksForGeeks_2", "GeeksForGeeks_3"); // Display the array elements print_r($Array); // Use foreach loop to remove array element foreach($Array as $k => $val) { if($val == "GeeksForGeeks_3") { unset($Array[$k]); } } // Display the array elements print_r($Array); ?> |
Array
(
[0] => GeeksForGeeks_1
[1] => GeeksForGeeks_2
[2] => GeeksForGeeks_3
)
Array
(
[0] => GeeksForGeeks_1
[1] => GeeksForGeeks_2
)
Example 2:
<?php // Declare an array and initialize it $Array = array( array(0 => 1), array(4 => 10), array(6 => 100) ); // Display the array elements print_r($Array); // Use foreach loop to remove // array element foreach($Array as $k => $val) { if(key($val) > 5) { unset($Array[$k]); } } // Display the array elements print_r($Array); ?> |
Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[4] => 10
)
[2] => Array
(
[6] => 100
)
)
Array
(
[0] => Array
(
[0] => 1
)
[1] => Array
(
[4] => 10
)
)
Recommended Posts:
- Iterate associative array using foreach loop in PHP
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- PHP | foreach Loop
- C# | Using foreach loop in arrays
- How to find the index of foreach loop in PHP ?
- Determine the first and last iteration in a foreach loop in PHP?
- How to remove an element from an array in JavaScript?
- ES6 | Array forEach() Method
- How to remove parent element except its child element using jQuery ?
- How to use loop through an array in JavaScript?
- How to loop through an associative array and get the key in PHP?
- How to reset/remove CSS styles for element ?
- How to remove an HTML element using JavaScript ?
- PHP | Separate odd and even elements from array without using loop
- Printing all subsets of {1,2,3,...n} without using array or loop
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


