How to go through and compare two arrays in PHP

Asked

Viewed 903 times

3

I have two arrays that return a Mysql query. I need to compare these two results to, every time they’re different, print something on the screen. The problem is that the query coming back from the database is an array with several fields, so I have to go through both.

I was trying to do this:

include_once 'classes/trabalhosclass.php';

if(!isset($_SESSION)){ session_start(); } 

$idTrabalho = $_SESSION['SemestreGeral'];
$Busca = '';
$oTrabalho = new trabalhosclass();
$oTrabalho -> listarAvancado($Busca, $idSemestre);          

while ($arrayTrabalhos = mysql_fetch_array($oTrabalho->retorno())){
    $array1[] = $arrayTrabalhos['orientador'];
}

include_once 'classes/professoresclass.php';

$aux = '';
$oProfessor = new professoresclass();
$oProfessor -> listar($aux);          

while ($arrayProfessores = mysql_fetch_array($oProfessor->retorno())){
    $array2[] = $arrayProfessores['Nome'];
}

$result = array_diff($array1, $array2);
print_r($result);

But it didn’t work... Would there be another way? I needed $result to show up all the names that are on one and not the other list...

  • 1

    The array_diff returns all names that are in the first but are not in the second. http://php.net/manual/en/function.array-diff.php

1 answer

2


Try it like this:

$result = array_diff (
   array_unique( array_merge($array1, $array2) ),
   array_unique( array_intersect( $array1, $array2 ) )
);
print_r($result);

See working on IDEONE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.