1

im having a list of names james,steve,manson,charles in a array and im using the explode function to separate them.

 $pieces = explode(",", $full);

foreach ($pieces as $p ){

    $piece[]=$p;
}

the problem that im having is that i can access the variables as

$piece[0];
$piece[1];

but the order differs time to time based on the input therefore i cant do a comparison. can someone suggest how to set the values so i can do the comparison as below

 if ($piece==='manson'){
//do something;
}else{
//do something
}

 if ($piece==='steve'){
//do something;
}else{
//do something
}
1
  • Looks like you are looking for switch? Commented Oct 7, 2011 at 18:30

1 Answer 1

5
$full = 'james,steve,manson,charles';
$pieces = explode(",", $full);

using a loop

foreach($pieces as $p ) {
    // $p holds the name
    if($p==='manson') {
        //do something;
    } elseif($p==='steve') {
        //do something;
    } else {
        //do something
    }
}

also you could just check for the name in the array instead of looping

if(in_array('steve',$pieces)) {
    echo 'We have Steve in the house';
}

or as Jon has suggested using a switch

foreach($pieces as $p) {
    switch ($p) {
        case 'manson':
        case 'steve':
        case 2:
            echo "Fist pump for ".$p;
            break;
        default:
            echo "no fist in the air";
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

the foreach if statement repeated same content but the in_array option worked perfectly.. Thank you very much...

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.