1

I have a php foreach loop that is displaying all my products on my store. The code looks like this:

 <?php foreach ($products as $product) { ?>

// getting products here

<?php } ?>

There are some products I wish not to show up in that loop, that I have the id's for, so I edited the Foreach loop like this:

<?php $ids = array(564,365,66,234,55); ?>

<?php foreach ($products as $product) { ?>
    <?php if(in_array($product['product_id'],$ids)) { ?>
          //getting products here
        <?php } ?>
<?php } ?>

This did just the opposite of what I wanted to do. I kinda knew it would. But I figured there is some way to reverse this and hide only those products. I was wondering if there was away to remove those products ids from the product array, and then continue the php loop getting all the other products. Any ideas? Thanks!

1
  • Do you actually want to remove the elements from the array, or just not display them? Commented May 2, 2014 at 13:06

4 Answers 4

6

Simply negate the condition:

if(!in_array($product['product_id'],$ids))
Sign up to request clarification or add additional context in comments.

Comments

3

You need to use the logical NOT operator, ! to only execute your code if the ID is NOT in the list.

<?php $ids = array(564,365,66,234,55); ?>

<?php foreach ($products as $product) { ?>
    <?php if(!in_array($product['product_id'],$ids)) { ?>
         // do operation
    <?php } ?>
<?php } ?>

Comments

2

Just use the !

So we are saying if the ids are not in the array it's cool to display them.

<?php $ids = array(564,365,66,234,55); ?>
<?php foreach ($products as $product): ?>
<?php if(!in_array($product['product_id'],$ids)):?>
  //show products that are not in array
<?php endif ?>
<?php endforeach ?>

Comments

2

If you plan on working with this reduced set later, you could use array_filter.

$filtered = array_filter($products, function($x) use($ids) { 
    return !in_array($x['product_id'], $ids); 
});

foreach ($filtered as $product) {
    // do operation
}

Comments

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.