-1

I would like to remove a certain value based on the value. Example in this situation, I would like to remove Tom from the array, then the next data will continue with the number that is previously used by Tom.

Here's my example:

    $array = array(0 => "Emily", 1 => "Tom", 2 => "Peter");
    if ($k = array_search($csR, $array)!==false)
            unset($array[$k]);

The outcome should be:

array(0 => "Emily", 1 => "Peter");
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
HelpNeeded
  • 33
  • 1
  • 1
  • 9

3 Answers3

3

Since you are using an indexed array, the best way to achieve this is to use array_values()

$csR = 'Tom';
$array = array(0 => "Emily", 1 => "Tom", 2 => "Peter");
if ($k = array_search($csR, $array)!==false)
{
    unset($array[$k]);
    $array = array_values($array);
}
print_r($array);
MonkeyZeus
  • 20,375
  • 4
  • 36
  • 77
1

Directly from the documentation of PHP: Arrays

Note: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>
Daniel Gale
  • 643
  • 4
  • 13
  • May I know is it possible if I would still like to have 3 keys in total after removing that the second key? – HelpNeeded Apr 07 '18 at 07:02
  • unset will remove the key meaning that you will have one less key. You could add the value back by using something like `$array[3] = 'four'` – Daniel Gale Apr 09 '18 at 14:51
0

You can get the difference between the array and an array with Tom or $csR and then re-index:

$array = array_values(array_diff($array, [$csR]));

However, there is rarely a need to have sequential keys. Have you tried foreach instead of for?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87