Remove the elements from array in php

<?php

$String_array=array(“a”,”b”,”c”,”d”);
$string_search=”c”;
echo “<pre>”;
print_r($String_array);
/*
OUTPUT OF print_r($string_array);
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
Now, We have to remove “c” value of element [2] from array
*/
 unset($String_array[array_search($string_search, $String_array)]);

/*
* From Above code  :
* first search the element from the array using array_search($value_to_be_search,$array) function
* if search found the give the integer value otherwise not.
* if found then it unset the value using unset($variable); function
**/
print_r($String_array);
/*
OUTPUT OF print_r($string_array);
Array
(
[0] => a
[1] => b
[3] => d
)
I don’t like this above output because array key index are not in proper manner.
*/
 $String_array = array_values($String_array);
 print_r($String_array);
/*
* From Above code :
* array_values($array) function  is used (simple language) to rearrage the elemenets keys
* If not used this function then above output will be given.
* Using this function I will get below output.
* Array
(
[0] => a
[1] => b
[2] => d
)
*
* This method is very simple and sweet.
* More Info. :  
* http://php.net/manual/en/function.array-search.php
* http://php.net/manual/en/function.array-values.php
* http://php.net/manual/en/function.unset.php
*/

?>


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *