PHP deleting elements of an array by unset ( key or value )

Array Unset We can remove an element from an array by using unset command. However unset command is used to destroy any other variable and same way we can use delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change. Let us see one simple example of this.
Here we are removing the element with key=3. If the array has 7 elements and if try to delete 9th element then unset command will not return any error but nothing will be deleted.

Here is an example how unset command is used.
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
As we are deleting the third element the output of above code is here.
0 -> a 
1 -> b
2 -> c
4 -> e
5 -> f
6 -> g

How to delete an element by using value ( not key ) from an array

In the above examples we have used key if the array as input to remove the element from the array. If we don't know the key and we know the value then how to remove the element? There is no direct function to do this but we can use array_diff function to remove the element by using the value. Note that array_diff function takes two arrays as input. Here is the code , we want to remove d from our $input array.
We can also use like this to remove more elements by using its value.
If you want you can display & check our elements like this.
while (list ($key, $val) = each ($new_array)) {
echo "$key -> $val <br>";}
The output of the above command is here
0 -> a 
1 -> b
3 -> d
4 -> e
6 -> g
You can read how unset a variable here.

Post your comments , suggestion , error , requirements etc here .

We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 All rights reserved worldwide Privacy Policy Disclaimer