-1

I am retrieving the data from database and these values are in array format and i want to compare both arrays

  $u1 = "meenu1294";
  $u2 = "pr3740";
  $sql = "SELECT managers FROM users WHERE id = '$u1'";
  $res = mysqli_query($con,$sql);
  while($r = mysqli_fetch_assoc($res))
  {
     $d = $r['managers'];
   }
  $sql1 = "SELECT managers FROM users WHERE id = '$u2'";
  $res1 = mysqli_query($con,$sql1);
  while($r1 = mysqli_fetch_assoc($res1))
  {
     $d1 = $r1['managers'];
  }

  $x = array_diff($d,$d1);
  echo json_encode($x);

But it shows like

** Warning: array_diff(): Argument #1 is not an array in C:\xampp\htdocs\ofppl\sample.php on line 19 **

Give me a suggestion Thanks in Advance

first query field answer is ["manomhae4006","pr3740"]

second query field answer is ["pr3740","gajaraja8196"]

but echo json_encode($x); shows ["[\"manomhae4006\",\"pr3740\"]"]

devpro
  • 16,184
  • 3
  • 27
  • 38
Meena Arumugam
  • 134
  • 3
  • 11

1 Answers1

2

array_diff() need both param as array and you are giving him a string.

You need to store values in an array something like:

$d[] = $r['managers'];
$d1[] = $r['managers'];

Example:

It's better to initiate before your while loop as:

$d = array(); // this will save empty array error.
while($r = mysqli_fetch_assoc($res))
{
    $d[] = $r['managers'];
}

And echo $x; will not give you nothing, array_diff() will return an array in result.

Side Note: Perform same activity for $d1

From PHP Manual: array_diff() Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

Edit: According to your edit, its not possible, as i check your code, its giving me this result:

<?php
$array1 = ["manomhae4006","pr3740"];
$array2 = ["pr3740","gajaraja8196"];
$diff = array_diff($array1, $array2);
echo "<pre>";
print_r($diff); // Result is Array ( [0] => manomhae4006  )

$jsonResult = json_encode($diff);
echo $jsonResult; // Result is ["manomhae4006"]
?>
devpro
  • 16,184
  • 3
  • 27
  • 38