How to remove specific element from an array in php

Here, we are fist adding array elements and then after addition of elements we are using array_search to get the key and remove it with unset if element is found

Example

<!DOCTYPE HTML>
<html>
	<head>
		<title>arrays elements addition and deletion</title>
	</head>
		<body>
		
			<?php
			// adding array elements initially
			$array = array("apple", "banana", "orange", "banana");
			var_dump($array); 
			
			array_push($array,"mango"); // add one element dynamically
			var_dump($array);
					
			// find an array element and then delete first occurrence
			if (($key = array_search('banana', $array)) !== false) {
				unset($array[$key]);
			}
		
			var_dump($array);
		
			?>
		</body>
</html>

Output



array (size=4)
  0 => string 'apple' (length=5)
  1 => string 'banana' (length=6)
  2 => string 'orange' (length=6)
  3 => string 'banana' (length=6)

array (size=5)
  0 => string 'apple' (length=5)
  1 => string 'banana' (length=6)
  2 => string 'orange' (length=6)
  3 => string 'banana' (length=6)
  4 => string 'mango' (length=5)

array (size=4)
  0 => string 'apple' (length=5)
  2 => string 'orange' (length=6)
  3 => string 'banana' (length=6)
  4 => string 'mango' (length=5)
Share

You may also like...