Biff Webster Jr.
Biff Webster Jr.

Reputation: 5

How do I test if a PHP variable is part of a specific array?

Basically I have this:

<?php
    $variable = 8;
    if ( $variable == array(5,6,7) ) :
    echo '<p>'.$variable.'</p>;
    endif;
?>

Can I test if a variable is one of those values like that or do I have to test each individually, like:

<?php
    $variable = 8;
    if ( ( $variable == 5 ) || ( $variable == 6 ) ) :
    echo '<p>'.$variable.'</p>;
    endif;
?>

Thanks.

Upvotes: 0

Views: 898

Answers (4)

Nobwyn
Nobwyn

Reputation: 8685

use in_array function for this

Upvotes: 1

Alex Turpin
Alex Turpin

Reputation: 47776

Use in_array:

if (in_array($variable, array(5, 6, 7))

Upvotes: 1

Colin Brock
Colin Brock

Reputation: 21575

I think you're looking for in_array():

if(in_array($variable, array(5,6,7) )){
    // $variable is in the array!
}

Upvotes: 3

baloo
baloo

Reputation: 7775

You can use in_array

if (in_array($variable, array(5,6,7))) {
    // do something
}

Upvotes: 3

Related Questions