0

i'm having trouble with how array works.

$a = array("24","33","12");
$b = array("24","12");

$c = array_intersect($a,$b);

echo json_encode($c);

// {"0":"24","2":"12"}

I expect the output to be like this:

// ["24","12"]

How can i achieve that output?

Jefsama
  • 553
  • 9
  • 29

2 Answers2

1

array_intersect Computes the intersection of arrays

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

will yield

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

. json_encode returns string containing the JSON representation of value. For example

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

will output

{"a":1,"b":2,"c":3,"d":4,"e":5}

As mamta answered you can use array_values to return all the values of an array and json_encode it like echo json_encode(array_values($c))

Tony Vincent
  • 13,354
  • 7
  • 49
  • 68
1
echo json_encode(array_values($c));

output

["24","12"]
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44