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

$input=array(a,b,c,d,e,f,g);
// Remove 4th element ( 0 indexed ) 
unset($input[3]); 
while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
As we are deleting the third element (4th on 0 index) the output of above code is here.
0 -> a 
1 -> b
2 -> c
4 -> e
5 -> f
6 -> g
Array Delete We can remove an element from an array by using unset command.
This unset command takes the array key as input and remove that element from the array. After removal the associated keys and values ( of other balance elements ) does not change.



Remove any element of PHP array by using unset, array_diff() or by searching for value & using key

unset($input[3]);
Array Unset 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.

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.
$new_array=array_diff($input,array("d"));
We can also use like this to remove more elements by using its value.
$remove=array(c,f);
$new_array=array_diff($input,$remove);
Display & check our elements after removal 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.

Using array_search()

We can use array_search() to get the key of matching search and then delete by using unset()
$input=array(a,b,c,d,e,f,g);

unset($input[array_search('d',$input)]);

while (list ($key, $val) = each ($input)) {
echo "$key -> $val <br>";
}
Output is here
0 -> a
1 -> b
2 -> c
4 -> e
5 -> f
6 -> g


Questions



Joining Two Arrays by array_merge
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





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