0

What is the best way to make sure that array $b has all the subarrays from $a despite the numeric keys (0,1,2.. etc)

$a = [
    0 => ['v' => 1, 'f' => 2],
    1 => ['v' => 144, 'f' => 443]
];

$b = [
    0 => ['v' => 1, 'f' => 2],
    1 => ['v' => 25, 'f' => 3],
    2 => ['v' => 144, 'f' => 443]
];

My approach with foreach inside foreach inside foreach and multiple ifs... quickly becomes a mess.

2 Answers 2

2

There is array_diff(), unfortunately this only works with 1 dimension. But you can json_encode() each element of the array and compare that...

$c = array_diff(array_map("json_encode", $a), array_map("json_encode", $b));

print_r($c);

With your original data, as they are all in the second array, this gives...

Array
(
)

Change the 443 to 4431

$a = [
    0 => ['v' => 1, 'f' => 2],
    1 => ['v' => 144, 'f' => 4431]
];

and you get...

Array
(
    [1] => {"v":144,"f":4431}
)

The key will be the same as the original, but the data is JSON encoded (if that really matters).

Sign up to request clarification or add additional context in comments.

Comments

0

You can use intersection in this case.

$a = [
    0 => ['v' => 1, 'f' => 2],
    1 => ['v' => 144, 'f' => 443]
];

$b = [
    0 => ['v' => 1, 'f' => 2],
    1 => ['v' => 25, 'f' => 3],
    2 => ['v' => 144, 'f' => 443]
];
$result = array_intersect($a, $b);
if($result == $a){
  echo '$b has all the value in $a';
}

2 Comments

This gives loads of Notice: Array to string conversion messages.
yes did not test before posting. The code should be $a = [ 0 => ['v' => 1, 'f' => 2], 1 => ['v' => 144, 'f' => 443] ]; $b = [ 0 => ['v' => 1, 'f' => 2], 1 => ['v' => 25, 'f' => 3], 2 => ['v' => 144, 'f' => 443] ]; $result = array_uintersect($a, $b, 'compareDeepValue'); if($result == $a){ echo '$b has all the value in $a'; } function valueCompare($val1, $val2) { return strcmp($val1['v'], $val2['v']) && strcmp($val1['f'], $val2['f']); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.