xxyoyoxx xxyoyoxx - 7 months ago 16
PHP Question

Compereing arrays and getting indexes

I got 2 arrays as $_SESSION value. They should be identical, but if they aren't I would like to check it in a function and as a result create third array with the indexes where values are not identical. For example:

$_SESSION['correctAnswers'] = ( [0] => 'horse' [1] => 'elephant' [3] => 'tiger' )

$_SESSION['usersAnswerArray'] = ( [0] => 'dog' [1] => 'cat' [3] => 'tiger' )

$result = ( [0] => 0 [1] => 1 )


Here is my function that do not work:

public function getWrongIndexes()
{
$index=0;
unset($licznik);
unset($indexes);

foreach($_SESSION['correctAnswers'] AS $correct)
{
if(trim($correct) != trim($_SESSION['usersAnswerArray'][$index]))
{
if(isset($indexes))
{
array_push($indexes,$index);
}else{
$indexes[0] = $index;
}
array_push($indexes,$index);
}
$index++;
}
print_r($indexes);
//return $indexes;
}


Is there any function that solve my problem? If not, how can I do this?

@edit Thanks for solving my problem

Could you help me with similar problem? Now from the array named $words I would like to get only these words that got indexes from array from your solution. All I got:

public function createNewWordsList($indexes)
{
$words = $this->wordsArray();
$licznik = 0;
$result = array();

foreach($words AS $i => $word)
{
if($i == $indexes[$licznik])
{
$licznik++;
$result[] = $word;
}
}
print_r($word);
}

Answer

This is slightly edited and will do what you need

public function getWrongIndexes()
{
    $indexes = array();

    foreach($_SESSION['correctAnswers'] AS $i => $correct)
     {
         if(trim($correct) != trim($_SESSION['usersAnswerArray'][$i]))
         {
            $indexes[] = $i;
         }
    }
    print_r($indexes);
    //return $indexes;
}

I have removed the second 'array_push($indexes,$index);' as that was not required, and using the keys from the first array, rather than a second '$index' variable.