How to Delete an Element From an Array in PHP?

03-Apr-2023

.

Admin

How to Delete an Element From an Array in PHP?

Hello Friends,

Now, let's see article of How to delete an Element From an Array in PHP. if you have question about How to remove an element from an array in PHP then I will give simple example with solution. We will look at example of How can we delete any element from an array in PHP. I would like to show you Deleting Elements from an Array.

This article will give you simple example of How to delete an Element From an Array in PHP?

So, let's see bellow solution:

Example 1:


<?php

$flowers = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy");

echo "Current Array :";

echo "<pre>";

print_r($flowers);

echo "</pre>";

echo "<br>";

$value = "Jasmine";

if (($key = array_search($value, $flowers)) !== false) {

unset($flowers[$key]);

}

echo("Array after deletion: \n");

echo "<pre>";

print_r($flowers);

echo "</pre>";

?>

Output:

Current Array :

Array

(

[0] => Rose

[1] => Lili

[2] => Jasmine

[3] => Hibiscus

[4] => Daffodil

[5] => Daisy

)

Array after deletion:

Array

(

[0] => Rose

[1] => Lili

[3] => Hibiscus

[4] => Daffodil

[5] => Daisy

)

Example 2:

<?php

$flowers = array(

"Rose",

"Lili",

"Jasmine",

"Hibiscus",

"Tulip",

);

echo "This is a Current Array :";

echo "<pre>";

print_r($flowers);

echo "</pre>";

$flowers = array_diff($flowers, array("Rose","Lili"));

echo "After Delete Element:\n";

echo "<pre>";

print_r($flowers);

echo "</pre>";

?>

Output:

This is a Current Array :

Array

(

[0] => Rose

[1] => Lili

[2] => Jasmine

[3] => Hibiscus

[4] => Tulip

)

After Delete Element:

Array

(

[2] => Jasmine

[3] => Hibiscus

[4] => Tulip

)

It will help you...

#PHP