Php Delete an element from array


Php Delete an element from array – You can remove array element using the unset($position) function. It deletes the element at the specified position. Here in this tutorial we are going to explain how you can delete an element form an array. We will explain this with example and demo.


Php Delete an element from array

You can remove an element from array using the unset function as below –

Php Delete an element from array Example:

<?php
$array = array("a","b","c","d");
print_r($array);
//now let us delete b
unset($array[1]);
print_r($array);

?>

Try it »

If you run the above example it will produce output something like this-

Php Delete an element from array


More Examples

Let’s have look over more example and demo here.


Php delete element from array by value

You can delete the array element by value as below –

Php delete element from array by value Example:

<?php
$array = array("a"=>'2',"c"=>'1',"d"=>'4',"e"=>'9');
print_r($array);
$delete_value = 4;
if(($key = array_search($delete_value, $array)) !== false) {
    unset($array[$key]);
}
echo "<h3>After Deleting</h3>";
print_r($array);
?>

Try it »

If you run the above example it will produce output something like this-

Php delete element from array by value Example:

Php delete element from array by key

You can delete the array element by key as below –

Php delete element from array by key Example:

<?php
$array = array("a"=>'2',"c"=>'1',"d"=>'4',"e"=>'9');
print_r($array);
$key = 'c';
    unset($array[$key]);
echo "<h3>After Deleting</h3>";
print_r($array);
?>

Try it »

If you run the above example it will produce output something like this-

Php delete element from array by value Example:


Advertisements

Add Comment

📖 Read More