1

Please I need to delete or update a data stored in an array for example:

$array = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');
$data_to_delete = 'Tuesday';
//possible explanation of code to run
if(in_array($data_to_delete, $array)){
    //run code to delete $data_to_delete from the $array
}
KANAYO AUGUSTIN UG
  • 2,078
  • 3
  • 17
  • 31

2 Answers2

3

Use the unset() command.

So to delete "Tuesday" you use:

$key = array_search("Tuesday", $array); 
if( $key !== false ) {
    unset(array_search("Tuesday", $array));
}

If you didn't know, array_search() returns key of the string it has found, so it is the equivalent of:

unset($array[1]);
Platinum Fire
  • 502
  • 3
  • 10
2
if(($i = array_search($data_to_delete, $array, true)) !== false) {
    unset($array[$i]);
}
splash58
  • 26,043
  • 3
  • 22
  • 34