Try this
<?php
$fruit = array('a' => "apple", 'b' => "banana", 'c' => "cranberry");
reset($fruit);
foreach($fruit as $key => $val)
{
if(($key=='a' && $val=="apple" ) || ($key=='b' && $val=="banana") )
{
echo "apple and banana";
}
}
?>
As the others have mentioned, when you write PHP you are not supposed to surround the sigit ($) with quotes.
Other then fixing that issue, I noticed another issue. When you are looping through the array, the $key
variable can only deal with one element at a time. In order for your programs if condition to be true, you required $key variable to have two values at the same time:
if(($key=="a" && $val=="apple" ) && ($key=="b" && $val=="banana"))
Notice the &&
. You are saying that $key
has to be equal to "a" and to "b" at the same time. $val also has to be equal to "apple" and "banana" at the same time. This condition is impossible.
Think of it this way. A variable is your hand. Your hand can only hold one thing at a time. $key
is your left hand, and $val
is your right. If I tell you that you can only enter my room if you are holding two things in your left hand and two things in your right hand, you will say to me, that is impossible! I can only hold one thing in my left hand, and only one thing in my right hand. This is a silly analogy but maybe it will help.
Anyway, that is why I changed the &&
to an ||
. In my code you may notice how I changed the array identifier (a
, b
, c
) from being surrounded in single quotes to double quotes. This is just my style. I like to do that.
Anyway, I hope this helps. Sorry if there are any spelling mistakes, I am in a rush and have to go.