All for Joomla All for Webmasters

Let's Play With Coding…

Delete an Element from Array

We can delete value in array using unset() function. If we know array key then we can easily use the function as follows

/**
 * CodeZone.in
 * Author : Dinesh Kumar
 * contact : hi@codezone.in
 */
 $example = array("X", "Y", "Z");

unset($example[1]);

//'dumps' the content of $example to the page:
var_dump($example);

Output of Var dump will be as follows

/**
 * CodeZone.in
 * Author : Dinesh Kumar
 * contact : hi@codezone.in
 */
array(2) { [0]=> string(1) "X" [2]=> string(1) "Z" }

Above said one is easy and straight forward but if we want to delete value without knowing key. Then it become tricky. To solve this puzzle we can use array_search() function

/**
 * CodeZone.in
 * Author : Dinesh Kumar
 * contact : hi@codezone.in
 */
 $delval='y'
 $example=array('x','y','z');
 if(($key = array_search($delval, $example)) !== false) {
    unset($example[$key]);
 }

In above code deletion of value done by searching value in array and find the key to delete the array value..

Tags: ,

Related posts

ASCII to HEX Convertion in PHP

We can delete value in array using unset() function. If we know array key then we can easily use the function as follows

Leave a Comment

Leave a Reply