Saturday, April 25

How to remove specific element from an array? Using PHP



$array = array('Apple', 'Orange', 'Strawberry', 'Blueberry', 'Kiwi', 'Mango');

echo "Initial array values </br>";
Print_r($array);

if (($key = array_search('strawberry', $array)) !== false) {
    unset($array[$key]);
}

echo "</br> Result </br>";
Print_r($array);


Initial array values
Array ( [0] => apple [1] => orange [2] => strawberry [3] => blueberry [4] => kiwi )
Result
Array ( [0] => apple [1] => orange [3] => blueberry [4] => kiwi )

 Note: Using unset in the array search option to resolve the problem

Second method to resolve the issue.


$myarray = array('Apple', 'Orange', 'Strawberry', 'Blueberry', 'Kiwi');
echo "Initial array values </br>";
Print_r($myarray);

foreach (array_keys($myarray, 'Strawberry') as $key) {
    unset($myarray[$key]);
}

echo "</br> Result </br>";
Print_r($myarray);

Initial array values
Array ( [0] => Apple [1] => Orange [2] => Strawberry [3] => Blueberry [4] => Kiwi )
Result
Array ( [0] => Apple [1] => Orange [3] => Blueberry [4] => Kiwi )



Note: Using unset option in Array key to resolve the issue

No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...