Reputation: 3
I am trying to add variable in an array but failed to do so please help me out.
Below is Original code which works fine
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
and it output this
Array
(
[a] => green
[0] => red
)
But I want to add variable in array so array gets value from the variable but it's not working
What I am trying
$a = '"green", "red", "blue"';
$b = '"green", "yellow", "red"';
$array1 = array("a" => $a);
$array2 = array("b" => $b );
$result = array_intersect($array1, $array2);
print_r($result);
I want it to output like this
Array
(
[a] => green
[0] => red
)
What I am getting
Array ( )
Any help will be appreciated. Thanks
Upvotes: 0
Views: 70
Reputation: 680
You are adding a string '"green", "red", "blue"' not an array. In your snippet
$a = '"green", "red", "blue"'; $b = '"green", "yellow", "red"'; $array1 = array("a" => $a); $array2 = array("b" => $w );
$result = array_intersect($array1, $array2); print_r($result);
PHP will understand $a
and $b
as strings. If you meant to pass an array to $a
and $b
you will need to change it to
$a = array("green", "red", "blue");
$b = array("green", "yellow", "red");
Then make your intersection. If you use an var_dump($a)
you will see that $a
is storing an String variable.
Upvotes: 1
Reputation: 28316
The code you have tried is assigning the string '"green", "red", "blue"'
to the array element "a"
when what you appear to want is to split the string like so that "green red blue"
becomes array("green","red","blue")
$a = "green red blue";
$array1 = split(" ",$a);
see http://php.net/manual/en/function.split.php
Upvotes: 1