ylli
ylli

Reputation: 53

compare arrays one by one

I have this output of arrays when I print_r The array from database

$answer --> Array ( [id] => 251 [question_id] => 242 [text] => something 
 [order] => 4 [deleted] => 0 )

and the array that comes what user selectes

//Array ( [0] => 254 [1] => 251 [2] => 252 [3] => 253 )

I need somehow to compare every answer that comes from db [id]=>251 to compare with [0] => 254what can I use, array_diff or intersect or another function, thank you

Upvotes: 0

Views: 73

Answers (6)

NiroshanJ
NiroshanJ

Reputation: 578

I created a function for check question id. Hope it will be useful

function checkAnswer($question1, $question2) {

    $indexed_array1 = array_values($question1);
    $indexed_array2 = array_values($question2);

    if ($indexed_array1[0]==$indexed_array2[0]) { // for check the answer && $indexed_array1[n]==$indexed_array2[n] | if the answer index is 'n'
        return true;
    }
    return false;
}

Upvotes: 0

Bibhudatta Sahoo
Bibhudatta Sahoo

Reputation: 4894

If your $answer array is multidimensional array the you can find the prent ids like this

$data= [['id' => 251 ,'question_id' => 242 ,'text' => 'something','order' => 4 ,'deleted' => 0 ]];
$selectors=[254,251,252,253];
$presentIds=[];
foreach ($selectors as $selector){
    if(in_array($selector,array_column($data,'id'))){
        $presentIds[]=$selector;
    }
}

Here $presentIds hold all the present ids.

Upvotes: 0

Zepp
Zepp

Reputation: 58

You can use array_search

Like that

$answer = Array ( 
    "id" => 251,
    "question_id" => 242,
    "text" => "something",
    "order" => 4,
    "deleted" => 0 
);

$ids= array(254,251,252,253);

$key = array_search($answer["id"], $ids);

if($key){
    echo "Find - Key: " . $key . " and ID: " $ids[$key];
}

Upvotes: 0

JYoThI
JYoThI

Reputation: 12085

simple use in_array function searches an array for a specific value

in_array($answer['id'],$selects);

Upvotes: 1

kunal
kunal

Reputation: 4248

Try This simple one

$answer = array('id'=>'251','question_id'=>'242','order'=>'4','deleted'=>0);
$answerArray  = array('254','251','252','253');

foreach ($answerArray as $key => $value) {
        if($answer['id'] == $value){
            echo "Right answer is". $value;
        }
}

Hope it helps!

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

You can use array_filter to filter the answers from db:

$myAnswers = array_filter($answers, function($answer) use ($selectedAnswers) {
    return in_array($answer['id'], $selectedAnswers);
});

var_dump($myAnswers);

Upvotes: 0

Related Questions