i am creating a multidimentional array and i wish to know why the following code is not working and why the other with same value when im fetching the same array is actually working.
$fruits = array(
"sale"=> array("banana", "apple", "orange"),
"regular"=> array("grapes", "pear", "ananas")
);
then in the first case it return false
1st case :
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
and in second example i got a result of true
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
in_array()
used to determine the value is in array or not. If you want to find if the key exist so array_key_exists
is your friend
Look at the below snippet.
$find_price = 'sale';
if(array_key_exists($find_price, $fruits)){
return true;
}
else {
return false;
}
In your first code
$find_price = 'sale';
if(in_array($find_price, $fruits)){
return true;
}
else {
return false;
}
You use in_array()
. This in_array()
function the elements into the array, That element exist in array or not. And you are finding a value which is key in the array. Instead of in_array()
you can use array_key_exists()
.
Your second code
$find_price = 'sale';
if(isset($fruit[$find_price])){
return true;
}
else {
return false;
}
You are using isset()
this function tell that the element you find, is exist in code or not. Like you are finding isset($fruit[$find_price])
means isset($fruit['sale'])
that is exist....
Thats why this condition is true..
You have to use loop for this type of conditions. try this.
foreach($fruits as $key => $value)
{
if($fruits[$key]['sale'])
{
return true;
}
else
{
return false;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.