0

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

5
  • Post expected output. Commented Jan 12, 2015 at 21:30
  • $w is undefined in this example &Of course the first preview is correct, as it's straight from the manual. What is your expected results? and what are you getting? Commented Jan 12, 2015 at 21:31
  • Added my expected output Commented Jan 12, 2015 at 21:32
  • @DarylGill sorry that's a typo Commented Jan 12, 2015 at 21:32
  • 1
    This looks like an XY problem. What are you actually trying to accomplish? Commented Jan 12, 2015 at 21:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.