Search code examples
phparraysmultidimensional-arrayfilteringreindex

Remove row elements of a 2d array by value and reindex


I have this array:

$array = [
    ['b', 'd', 'c', 'a', ''],
    ['c', 'a', 'd', '', ''],
    ['b', 'd', 'a', '', ''],
    ['c', 'd', 'a', 'b', '']
];

and need to delete (unset?) all elements where value is "c" so that one ends up with:

$array = [
    ['b', 'd', 'a', ''],
    ['a', 'd', '', ''],
    ['b', 'd', 'a', '', ''],
    ['d', 'a', 'b', '']
];

The element gets removed, and the other elements to shift up. I know that unset does not re-index the array. Cannot get to unset for all multidimensional arrays, but only with one array. Can the arrays be re-indexed afterwards?

The code BELOW removes elements where the value is equal to "c" but the index of the first element is not re-indexed. Can anyone suggest a solution to re-indexing the inner arrays?

$i = 0;
foreach ($array as $val)
{
    foreach ($val as $key => $final_val)
    {
        if ($final_val == "$search_value") 
        {
             unset($array[$i][$key]);
        }
    } 
    $i = $i + 1;
}

Solution

  • The following code will do what you want:

    <?php
    $a = 1;
    $b = 2;
    $c = 3;
    $d = 4;
    
    $arr = array(
    array ( $b, $d, $c, $a, $b),
    array ($c, $a),
    array ( $b, $d,  $c ),
    array( $c, $d, $a, $b, $b)
    );
    echo "before:\n";
    print_r($arr);
    
    foreach($arr as $k1=>$q) {
      foreach($q as $k2=>$r) {
        if($r == $c) {
          unset($arr[$k1][$k2]);
        }
      }
    }
    echo "after:\n";
    print_r($arr);
    ?>
    

    Output:

    before:
    Array
    (
        [0] => Array
            (
                [0] => 2
                [1] => 4
                [2] => 3
                [3] => 1
                [4] => 2
            )
    
        [1] => Array
            (
                [0] => 3
                [1] => 1
            )
    
        [2] => Array
            (
                [0] => 2
                [1] => 4
                [2] => 3
            )
    
        [3] => Array
            (
                [0] => 3
                [1] => 4
                [2] => 1
                [3] => 2
                [4] => 2
            )
    
    )
    after:
    Array
    (
        [0] => Array
            (
                [0] => 2
                [1] => 4
                [3] => 1
                [4] => 2
            )
    
        [1] => Array
            (
                [1] => 1
            )
    
        [2] => Array
            (
                [0] => 2
                [1] => 4
            )
    
        [3] => Array
            (
                [1] => 4
                [2] => 1
                [3] => 2
                [4] => 2
            )
    
    )
    

    As you can see, all the 3's have gone...