How to do a php array?

How can I do this…

<?php if ($_product->getCatIndexPosition() === '0'): ?>
do something
<?php else: ?>
do something else
<?php endif; ?>

but I need it to be == 0, 1, or 2

thanks

<?php if ($_product->getCatIndexPosition() == '0' OR $_product->getCatIndexPosition() == '1' OR $_product->getCatIndexPosition() == '2'): ?>
do something
<?php else: ?>
do something else
<?php endif; ?>

I prefer to use the double equal signs. I never use triple equal signs for comparing because it can sometimes fail or maybe even return the wrong results. Only when I use strpos do I ever use triple equal signs or the third operator.

Adding ORs to the conditional is the logical first choice.
But I would be tempted to define an array of values and use in_array if there was a chance that there might be more values to test for just to keep the code neater.

2 Likes

If I understand you then the following is closer to what you want:

<?php
switch ($_product->getCatIndexPosition()) {
    case '0':
        echo "Do whatever for 0";
        break;
    case '1':
        echo "Do whatever for 1";
        break;
    case '2':
        echo "Do whatever for 2";
        break;
}
?> 

I have not tested that code but I hope it is close enough for you to use.

Thanks spaceshiptrooper I tried it and it works.

Here’s a follow up on @Mittineague’s post.

<?php
$needle = 0;

$haystack = array(0, 1, 2);

if(in_array($needle, $haystack)) {

    print('Do something');

} else {

    print('Do something else');

}
?>

As you can see, our needle (in your case, $_product->getCatIndexPosition()) is set to an integer of 0. We then create our haystack (in your case, whatever array you want) of integers that you may desire. Then, we check to see if our needle is within the haystack. If the needle is not, we’ll output Do something else. If it is within our haystack, we’ll output Do something. Since the integer of 0 is within our haystack, it is found.

1 Like

I am confused :frowning:

The original post tested for a single character and later asked to test for the integers 0,1 and 2.

I think there could be problems.

1 Like

I am confused too. It looks like the OP was for string integers, but then asked for integers 0, 1, or 2 within the condition.

Assuming the OP was asking for a condition to check whether those 3 integers were pulled from the needle, then the array approach would suit.

But if the OP was asking for a condition in which the third operator is also checked, I still don’t think that would be best. I just tried testing the third operator and it throws me the Do something else line which probably isn’t what the OP was looking for. Then I tested it with double equal signs instead and it threw the Do something condition.

So assuming the OP was asking for all 3 integers to display the same message Do something, then the array approach could suit.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.