Search code examples
phparraysloopsforeachunset

How do I remove one array from another in php?


I have the following arrays in PHP: print_r($employees) =

Array
(
    [0] => Array
        (
            [p_id] => T29083999
            [name] => Robert Plaxo
        )

    [1] => Array
        (
            [p_id] => T29083388
            [name] => Yvan Sergei
        )

    [2] => Array
        (
            [p_id] => T21083911
            [name] => Rhonda Saunders
        )

    [3] => Array
        (
            [p_id] => H02910382
            [name] => Miguel Mercado
        )
)

then this array: print_r($record) =

Array
(
    [0] => Array
        (
            [c_id] => 1
            [section] => 1061
            [term] => 201631
            [p_id] => T29083388
            [c_date] => 2016-04-01 09:14:00
        )

)

I want to remove the array element from $employees that matches the p_id of $record. Array $record may have multiple entries like the one shown. If so, any p_id in $record must be removed from $employees.

I tried:

foreach ($employees as $k => $e) {
    foreach ($record as $r) {
        if ($e['p_id']==$r['p_id']) {
            echo "found it!";
            // if I uncomment the next line, it crashes! (500 server error)
            //  unset $employees[$k];
        }           
    }   
}

I just want to remove any element from $employees that has any employee that matches any record in $record with that employee id.


Solution

  • You were almost there; just needed parens around your unset()

    I also took the liberty to change some of your variable names as single character variable names bother me.

    $employees[] = [
        'p_id' => 'T29083999',
        'name' => 'Robert Plaxo',
    ];
    $employees[] = [
        'p_id' => 'T29083388',
        'name' => 'Yvan Sergei',
    ];
    $employees[] = [
        'p_id' => 'T21083911',
        'name' => 'Rhonda Saunders',
    ];
    $employees[] = [
        'p_id' => 'H02910382',
        'name' => 'Miguel Mercado',
    ];
    
    $records[] = [
            'c_id' => '1',
            'section' => '1061',
            'term' => '201631',
            'p_id' => 'T29083388',
            'c_date' => '2016-04-01 09:14:00',
    ];
    
    foreach ($employees as $key => $employee) {
        foreach ($records as $record) {
            if ($employee['p_id'] == $record['p_id']) {
                echo "found it!";
                unset($employees[$key]);
            }
        }
    }
    
    echo "<pre>";
    print_r($employees);
    

    Outputs

    found it!
    
    Array
    (
        [0] => Array
            (
                [p_id] => T29083999
                [name] => Robert Plaxo
            )
    
        [2] => Array
            (
                [p_id] => T21083911
                [name] => Rhonda Saunders
            )
    
        [3] => Array
            (
                [p_id] => H02910382
                [name] => Miguel Mercado
            )
    
    )