Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kingjmaningo/91c3a2b1663cf18df53c834fcb204888 to your computer and use it in GitHub Desktop.
Save kingjmaningo/91c3a2b1663cf18df53c834fcb204888 to your computer and use it in GitHub Desktop.
Remove an element from an array if certain value matched
<?php
// **** For simple array
// Delete value 2 in the array
$id = 2;
$simple_array = array(1, 2, 3);
$key = array_search($id, $array);
unset($array[$key]);
// We are expecting to remove id #2. To check:
print_r($array);
// **** For multi-dimentional array
$position = 'SG';
// We are trying to remove an array that matched the position
$array_values = array (
array(
'id' => 1,
'name' => 'Kobe',
'position' => 'SG',
'birth_date' => '10-22-2019' ),
array(
'id' => 2,
'name' => 'Lebron',
'position' => 'SF',
'birth_date' => '11-01-2019' ),
array(
'id' => 3,
'name' => 'Mike',
'position' => 'SG',
'birth_date' => '10-18-2019' ),
array(
'id' => 4,
'name' => 'Magic',
'position' => 'PG',
'birth_date' => '10-11-2019' )
);
foreach($array_values as $key => $value) {
if ($value['position'] == $position) {
unset($array_values[$key]);
}
}
// We are expecting to remove players that have 'SG' positions. To check:
echo '<pre>';
print_r($array_values);
echo '<pre>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment