Max Rose-Collins
Max Rose-Collins

Reputation: 1924

removing a value from an array if it does not equal a value in another array in PHP

I have an array like this

Array
(
    [0] => Array
        (
            [0] => 83
            [1] => 82
            [2] => 81
        )

    [1] => Array
        (
            [0] => 81
            [1] => 82
            [2] => 83
            [3] => 100
            [4] => 101
            [5] => 102
            [6] => 103
            [7] => 104
            [8] => 105
        )

)

and I want to delete any values from the first array that are not equal to this array

Array
(
    [0] => 83
    [1] => 82
    [2] => 81
)

But i want to keep the same structure as the first array. So i would end up with something like this

Array
(
    [0] => Array
        (
            [0] => 83
            [1] => 82
            [2] => 81
        )

    [1] => Array
        (
            [0] => 81
            [1] => 82
            [2] => 83
        )

)

What is the best way to achieve this?

Upvotes: 1

Views: 2148

Answers (4)

sgb
sgb

Reputation: 2374

if $array is your starting array and $matches is the array of values you want to match;

foreach ($array as $key => $subarray) {
    foreach ($subarray as $subsubarray) {
        foreach ($matches as $match) {
            if ($subsubarray == $match) {
                $finalarr[$key][] = $subsubarray;
            }
        }
    }
}

$finalarr will be your desired result.

Upvotes: 2

Nick
Nick

Reputation: 84

$temp = array
(
    0 => array
    (
        0 => 83,
        1 => 82,
        2 => 81
    ),

    1 => array
    (
        0 => 81,
        1 => 82,
        2 => 83,
        3 => 100,
        4 => 101,
        5 => 102,
        6 => 103,
        7 => 104,
        8 => 105
    )

);

for($i=0,$tot = count($temp[1]);$i<$tot;$i++)
{
    if(!in_array($temp[1][$i],$temp[0]))
    {
        unset($temp[1][$i]);
    }
}

Upvotes: 0

hsz
hsz

Reputation: 152304

$data = array( /* your data you want to check (first big array) */ );
$test = array( 83, 82, 81 );

foreach ( $data as $key => $value ) {
  $intersect = array_intersect($value, $test);
  if ( $intersect != $test ) {
    unset($data[$key]);
  } else {
    $data[$key] = $intersect;
  }
}

Upvotes: 4

Tom
Tom

Reputation: 1711

You can always set the array to be the intersection of the first and second one with the array_intersect function.

<?php
$array[1] = array_intersect($array[0], $array[1]);
?>

Upvotes: 1

Related Questions