0
function CHECKITEMEXIST($cartarray, $sub){
    foreach ($cartarray as $item){
        foreach ($item as $item2){
            if($item2['subject'] = $sub){
                return '1';

            }else{
                return '0';
            }
        }
    }
}

$subject = "English";
    $checkitemexist = CHECKITEMEXIST($cart, $subject);

if($checkitemexist > 0){
    echo "Yes";
}else{
    echo "No";
}

Guys I have the function below to check my cart array to see whether english subject exist or not, but the problem is even when english isn't in the cart array it will still return yes result, why is that so?

Below are the sample cart array.

Array ( [0] => Array ( [0] => Array ( [subject] => science ) ) )
3
  • 1
    You return '0' and '1', you should change that to 0 and 1. Stick with integers as much as you reasonably can (for performance). Also, on line4 on the 2nd piece of code you do >0. I suggest either !==0 or ===1. These are a tiny bit faster, but I personally because IMO it reads easier Commented Feb 25, 2014 at 10:07
  • Or even better, return true/false and do if( $checkitemexist ){ Commented Feb 25, 2014 at 10:08
  • I tried. The first value I pass in English, it will return yes, but the second value I pass in Science which is also in the cart array it returns no. I don't understand. Commented Feb 25, 2014 at 10:21

1 Answer 1

1

make it correct

if($item2['subject'] = $sub){   // = is an assignment operator

to

if($item2['subject'] == $sub){  // == is a comparison operator

UPDATE 2 :

try your modified function

function CHECKITEMEXIST($cartarray, $sub){
$flag = 0;
    foreach ($cartarray as $item){
        foreach ($item as $item2){
            if($item2['subject'] == $sub){
                $flag = 1;
            break;
            }
        }
        if($flag==1)
        {
            break;
        } 
    }
return $flag;   
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried. The first value I pass in English, it will return yes, but the second value I pass in Science which is also in the cart array it returns no. I don't understand.

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.