Author -  Sai gowtham

How to remove the element from an array by value in PHP

To remove the element from an array by value, we can use the combination of array_search() and unset() functions in PHP.

Here is an example, that removes the second element "green" from the colors array by value.

<?php
$colors = array("red", "green", "yellow", "orange");

if (($key = array_search("green", $colors)) !== false) {
    unset($colors[$key]);
}

print_r($colors)
?>

Output:

Array
(
    [0] => red
    [2] => yellow
    [3] => orange
)

The unset() function doesn’t re-index the array keys, if you want to re-index it then you can use the array_values() function after unset().

<?php
$colors = array("red", "green", "yellow", "orange");

if (($key = array_search("green", $colors)) !== false) {
    unset($colors[$key]);
}

print_r(array_values($colors))
?>

Similarly, we can also use the array_diff() function like this to remove it.

$colors = array("red", "green", "yellow", "orange");

$newArray = array_diff($colors, array("green"));

print_r($newArray)

You can also use the array_diff() function to remove multiple elements by using value.

$colors = array("red", "green", "yellow", "orange");

$newArray = array_diff($colors, array("green", "yellow"));

print_r($newArray)

Note: The array_diff() function creates a new array by preserving the original array, where the first solution modifies the original array.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY