How to Remove a Specific Element From an Array in PHP

Hello Dev, Today we are going to learn How to Remove a Specific Element From an Array in PHP. Here you will learn how to delete an element from arrays, how to remove a elements from an arrays in php.

Learn how to remove a specific elements from array in php with example. We will show you how you can remove elements from an array in php 8.

Here, I will show you How to delete an Element From an Array in PHP. step by step explain How to remove element from an array in php. I would like to show you How can we delete any element from an array in PHP. step by step explain Deleting Elements from an Array. So, let’s follow few step to create example of PHP deleting elements of an array by unset ( key or value ).

Also Read: Laravel 9 Vue JS CRUD App using Vite Example

How to Remove a Specific Element From an Array in PHP Examples:

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
)

Also Read: Laravel 9 Livewire Multi Step Form Wizard Tutorial

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
)

Conclusion

Today, We had learn How to Remove a Specific Elements From an Array in PHP. Hope this tutorial helped you with learning PHP. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Laravel 9 Livewire Datatables Example

6 Comments

Leave a Reply