Nick
Nick

Reputation: 1999

Check if $var = anything in an array?

I need to be able to test if $post_count is equal to any number in a given array. Here is an example of what I am trying to achieve:

$posts_even = array(2,4,6,8,10);
$posts_odd = array(1,3,5,7,9);
$posts_ev3 = array(1,4,7,10);
$posts_ev4 = array(1,5,9);

--

$post_count=1;
$post_count=++; //in wordpress loop so each subsequent post is +1

--

if ($post_count= //any value in $posts_ev4) :
    echo 'this'
else :
    NULL;
endif;

I have been able to make this work using the or operator but I end up with very long blocks of code.....

if (($post_count=1) || ($post_count=2)) :
    echo 'this'
else :
    NULL;
endif;

I am guessing there is a simpler way to do this but I am new to PHP so I am not sure! Any help would be greatly appreciated.

Upvotes: 0

Views: 229

Answers (5)

Nishu Tayal
Nishu Tayal

Reputation: 20880

There are array functions in php. Ypu can use "is_array" function to check whether its array or not. & to check for a value you can use "in_array" function.

if(is_array($array) && in_array($post_count,$array))
{  
   // do operation
}

Upvotes: 1

Max
Max

Reputation: 38

Check out the isset() function in the PHP Manual.

Upvotes: 1

Jonathan Spooner
Jonathan Spooner

Reputation: 7752

Try:

if (in_array($post_count, $post_ev4)) {}

See: in_array()

Upvotes: 3

Shef
Shef

Reputation: 45599

if (in_array($post_count, $posts_ev4)) :
    echo 'this'
else :
    NULL;
endif;

Upvotes: 1

Riz
Riz

Reputation: 10246

Use in_array() to check if value exists in array.

Upvotes: 3

Related Questions