0

I have two array i.e $arr1 and $arr2 where I want to find missing value of $arr1 which is not present in $arr2 without using function like array_diff(), count(), explode(), implode() etc. So, How can I do this? Please help me.

code:

<?php
    $arr1 = array('2','3','4','5');
    $arr2 = array('1','6','7','8');

    $array = array_diff($arr1,$arr2);
    print_r($arr2);
?>
2
  • 1
    so what you have tried so far? Commented Jul 6, 2019 at 5:39
  • I am simply use array_diff() function to find missing value of an array but I want to do without any function @AlivetoDie Commented Jul 6, 2019 at 5:42

2 Answers 2

1

First approach:-

$missingValuesArray = array();
    foreach($arr1 as $arr){
       if(!in_array($arr,$arr2)){
           $missingValuesArray[] = $arr;
       }
    }

    print_r($missingValuesArray);

Output:- https://3v4l.org/UBS9G

Second approach:-

 $missingValuesArray = array();
    foreach($arr1 as $arr){
        $counter = 0;
        foreach($arr2 as $ar){
           if($arr != $ar){
               $counter++;
           }
        }
        if($counter == sizeof($arr2)){
            $missingValuesArray[] = $arr;
        }
    }

    print_r($missingValuesArray);

Output:- https://3v4l.org/Uu6Ob

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

3 Comments

in the first approach, you are using an in_array() function.
@RajendraSingh i gave him all approaches what came into my mind apart from array_diff().It's up to him to select any one or discard all
Yeah, I think Second approach suits user requirement. The first approach with in_array() is also good but it's same like user attempt with array_diff()
1

Requirement can be achieved by :

$arr1 = array('2','3','4','5');
$arr2 = array('1','6','7','8');

$diff = array();
$diff = $arr1;
$arrayDiff = array();

foreach($arr1 AS $value) {
    foreach($arr2 AS $val) {
        if ($value == $val) {
           $arrayDiff[] = $value;
           continue;
        }
    } 
}
foreach ($arrayDiff AS  $k=>$v) {
    if (($key = array_search($v, $diff)) !== false) {
        unset($diff[$key]);
    }
}
print_r($diff);

1 Comment

you are using array_search()

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.