LiveEn
LiveEn

Reputation: 3253

compare array values for a if statement php

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
}

Upvotes: 1

Views: 3787

Answers (1)

Phill Pafford
Phill Pafford

Reputation: 85308

$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";
    }
}

Upvotes: 5

Related Questions