Reputation: 44086
I have this if statement
<?php if(in_array($product['product_id'], $selected_products['business'])) { ?>
but sometimes the array $selected_products
doesnt have the index business
.. how can i alter the if condition without have an outer if statement
Upvotes: 0
Views: 88
Reputation: 655707
Use the logical AND operator &&
to combine both expressions:
if (array_key_exists('business', $selected_products) && in_array($product['product_id'], $selected_products['business']))
Upvotes: 2
Reputation: 14159
You could use a ternary statement, that line will be a bit busy though:
<?php if(in_array($product['product_id'], isset($selected_products['business']) ? $selected_products['business'] : false))) { ?>
Upvotes: 1
Reputation: 53921
Short circuit isset
using the && operator. With short circuit evaluation, the second expression isn't evaluated if the first one fails.
<?php if(isset( $selected_products['business']) && in_array($product['product_id'], $selected_products['business'])) { ?>
Upvotes: 3
Reputation: 724402
It depends on what you want to do if the index doesn't exist.
If you only want to perform this check if the index is there, add an isset()
check before it (line break for clarity):
if (isset($selected_products['business'])
&& in_array($product['product_id'], $selected_products['business'])) {
Additionally, if you need to do something else in the event the index isn't there, attach an else
block.
Upvotes: 3