Overview:
In PHP, an associative array is an array that uses named keys instead of numerical indices. To delete an associative element from an array, you can use the unset() function. The unset() function is a PHP built-in function that removes a variable, an array element or a property of an object. It takes one or more arguments and returns NULL.
Here’s the syntax of the unset() function:
unset($array[key]);
Where $array
is the name of the array and key
is the key of the element you want to delete.
Example of deleting an associative element:
Let’s take a look at an example to see how to delete an associative element from an array in PHP:
// Define an associative array
$fruits = array(
"apple" => "red",
"banana" => "yellow",
"orange" => "orange",
"grape" => "purple"
);
// Delete the element with the key "orange"
unset($fruits["orange"]);
// Output the updated array
print_r($fruits);
Output:
Array
(
[apple] => red
[banana] => yellow
[grape] => purple
)
In this example, we defined an associative array $fruits
with four elements. We then used the unset()
function to delete the element with the key "orange"
. Finally, we used the print_r()
function to output the updated array, which no longer contains the "orange"
element.
That’s it! You now know how to delete an associative element from an array in PHP using the unset()
function.