0

If there are two array variable which contains exact same digits(no duplicate) but shuffled in position.

Input arrays

arr1={1,4,6,7,8};
arr2={1,7,7,6,8};

Result array

arr2={true,false,false,false,true};

Is there a function in php to get result as above or should it be done using loop(which I can do) only.

4
  • You'll have to do it yourself in a loop. PHP has a ton of helper functions, but don't expect to find a ready-made house, when you're given a hammer already. Commented Aug 5, 2011 at 19:42
  • These arrays do not have the same exact digits; arr2 has duplicates. Commented Aug 5, 2011 at 19:47
  • @js1568 no duplicate means in both arrays digits are unique in their own. Commented Aug 5, 2011 at 19:55
  • @kiranking arr2={1,7,7,6,8}; has two 7s. Commented Aug 5, 2011 at 19:57

5 Answers 5

3

This is a nice application for array_map() and an anonymous callback (OK, I must admit that I like those closures ;-)

$a1 = array(1,4,6,7,8);
$a2 = array(1,7,7,6,8);

$r = array_map(function($a1, $a2) {
    return $a1 === $a2;
}, $a1, $a2);

var_dump($r);

/*
array(5) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
  [3]=>
  bool(false)
  [4]=>
  bool(true)
}
*/

And yes, you have to loop over the array some way or the other.

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

Comments

3

You could use array_map:

<?php

$arr1= array (1,4,6,7,8) ;
$arr2= array (1,7,7,6,8) ;

function cmp ($a, $b) {
    return $a == $b ;
}

print_r (array_map ("cmp", $arr1, $arr2)) ;
?>

The output is:

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

Comments

1

Any way this job is done must be using looping the elements. There is no way to avoid looping.

No metter how you try to attack the problem and even if there is a php function that do such thing, it uses a loop.

Comments

0

You could use this http://php.net/manual/en/function.array-diff.php, but it will not return an array of booleans. It will return what data in array 1 is not in array 2. If this doesn't work for you, you will have to loop through them.

Comments

0

there's array_diff() which will return an empty array in case they are both equal.

For your spesific request, you'll have to iterate through the arrays and compare each item.

Comments

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.