what if the index doesnt exist - php

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

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.

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'])) { ?>

Use the logical AND operator && to combine both expressions:
if (array_key_exists('business', $selected_products) && in_array($product['product_id'], $selected_products['business']))

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))) { ?>

Related

I want use && operator and Not operator at the same time in IF statement

I want use && operator and Not operator at the same time in IF statement. If it is possible then how to write it. Below is the statement which i have written is it right?
if(!$row['sl_name'] && !$row['sn_name']){
}
You can write like this if you wish to check for blank variables:
if(!empty($row['sl_name']) && !empty($row['sn_name'])){
}
else{
}
It checks for both the variables are not empty if anyone of them is empty it goes to else part.

PHP If (!isset(...) || !isset(...))

I'm trying to check if the first $_COOKIE['one'] exists OR the second $_COOKIE['two'] exists and if none exists to redirect the user.
Only one of those two cookies are going to exist when this script is running.
if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
header('Location: ./');
} else {
...
}
I tried many things but every time I get into this if altough one of those cookies always exist.
This is a simple case of inverted logic. As Mark pointed out, you need to be using the boolean && (AND) operator. You are trying to see if both don't exist, then send the header. Currently, if either exists, you send the header anyway.
Just change if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
to
if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
Or (||) returns true if either the left or right of the statement is true. And (&&) returns true only if both parts of the statement are true. The Not(!) operator reverses true->false and false-> true.
isset tells you if the cookie exists. If the cookie exists, it returns true. You are correct in using not on this, as you want it to tell you if the cookie doesn't exist (opposite). However, you only want to send the header if BOTH cookies don't exist. Or will send it if one doesn't exist.
You wrote an opposite logic to what you really want.
You said that
You're trying to check if
That's an if conditional.
the first $_COOKIE['one'] exists
For that you use isset, which you did and it's right.
OR the second $_COOKIE['two'] exists
So you'd use the OR operator ( || )
and if none exists to redirect the user.
That's an else, and then use header to redirect.
Converting your words to literal code, you'd have this:
if (isset($_COOKIE['one']) || isset($_COOKIE['two'])) {
//... Do your thing
} else {
header('Location: ./');
}
Your code also works with the fix provided by Mark in the comments, but might confuse you in the future...
You can also do this to avoid nesting:
if (!(isset($_COOKIE['one']) || isset($_COOKIE['two']))) {
{
header('Location: ./'); exit;
}
//... Do your thing
If only one of the cookies will ever be set then then your if condition will always be true so the redirect will happen.
Change || for &&,
if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
header('Location: ./');
} else {
//
}
More elegantly, isset() can handle muliple arguments and negating its return value will give you exactly what you want.
Code: (Demo)
var_export(!isset($cookie1, $cookie2)); // Are either missing? Yes, both are missing.
echo "\n";
$cookie1 = 'declared';
var_export(!isset($cookie1, $cookie2)); // Are either missing? Yes, one is missing.
echo "\n";
$cookie2 = 'declared';
var_export(!isset($cookie1, $cookie2)); // Are either missing? No, neither are missing.
Output:
true
true
false

Second check in or-statement not executed

In my php application i do the following check:
if(($images = $main->get_images($data['id'])) || ($videos = $main->get_videos($data['id']))){
(...)
if($videos){
(...)
}
if($images){
(...)
}
}
This operation sends back an error saying $videos is undefined. My guess is that if the first statement is true, the second wont be checked. Is there any neat way of preforming the second check, even is the first one is true, because in this case if images is true, videos will be evaluated as false
There isn't a way. You'll need to re-write it into something like this...
$images = $main->get_images($data['id']);
$videos = $main->get_videos($data['id']);
if($images || $videos){
(...)
if($videos){
(...)
}
if($images){
(...)
}
}
And just FYI... order of operations means you don't need to enclose the conditions in () brackets. Almost everything gets computed BEFORE the OR operator (including the && operator).
Good luck!
Joey
You can use empty() to see if a variable does not exist or is null e.g.
if(!empty($videos)) {
(...)
}

PHP If a variable equals this or this

I have this if statement in my PHP:
if($_SESSION['usrName']!='test1'){
header('location:login.php');
}
But i want it to be something like this:
if($_SESSION['usrName']!='test1' or 'user'){
header('location:login.php');
}
But i cant figure out how to do it in PHP code. I have tried this:
if($_SESSION['usrName']!='test1','user'){
header('location:login.php');
}
And this:
if(($_SESSION['usrName']!='test1')||($_SESSION['usrName']!='user')){
header('location:login.php');
}
Can anybody help please?
You have to replace the || with &&. Because you only want to redirect when both conditions are true.
if(($_SESSION['usrName']!='test1') && ($_SESSION['usrName']!='user')){
header('location:login.php');
}
if (!in_array($_SESSION['usrName'], array('test1', 'user')) {
header('location:login.php');
}
This checks if variable $_SESSION['usrName'] is not in list of strings to simplify additional allowed user.
As others have said, you need to be careful with your boolean logic - (NOT X) || (NOT Y) is equivalent to NOT (X AND Y), whereas what you want is NOT (X OR Y) which is equivalent to (NOT X) AND (NOT Y).
For this particular situation, there are also a couple of other options, although none as neat as the invalid syntaxes you tried.
First, there is in_array(), which is easy to read, but not very efficient if you use it a lot with long lists (for a simple case like this, it's not worth worrying about performance, though):
$allowed_users = array('test1', 'user');
if ( ! in_array($_SESSION['usrName'], $allowed_users ) { ... }
Or, you can build a hash with the usernames as keys; this is more efficient as the list grows, because PHP can check for a key without looping through the whole list:
$allowed_users = array('test1' => true, 'user' => true);
if ( ! array_key_exists($_SESSION['usrName'], $allowed_users) ) { ... }
// Or, if you don't mind PHP raising a few notices about accessing undefined keys
if ( ! $allowed_user[ $_SESSION['usrName'] ] ) { ... }
Finally, you can use a switch statement, with the labels falling through, and a default case acting as the "else":
switch ( $_SESSION['usrName'] )
{
case 'test1':
case 'user':
// These users are allowed :)
break;
default:
header('location:login.php');
}
Which, if any, of these you choose to use will depend on how you expect the code to grow in future, but they're useful tricks to know.
Your last attempt is almost correct.
However...
if (var != something || var != something-else)
...will always be true, because one of those conditions will always match. Even if it's equal to one side, it won't be equal to the other.
When you're testing two negatives like that, you need to use AND (&&) instead of OR (||).
if (($_SESSION['usrName']!='test1') && ($_SESSION['usrName']!='user'))
This will match if it's not equal to one, and also not equal to the other.
Currently, you're checking if either one of conditions are true. The last condition will evaluate to true if either one of the conditions are correct. I assume you're trying to check if both the the conditions are true. In that case, you'll need && instead of ||.
Try:
if( ($_SESSION['usrName'] != 'test1') && ($_SESSION['usrName'] != 'user') ) {
header('location:login.php');
}
You need to do something like:
if($_SESSION['usrName'] != 'test1' and $_SESSION['usrName'] != 'user'){
header('location:login.php');
}
The first attempt of yours is equivalent to:
if(($_SESSION['usrName']!='test1') or 'user'){
header('location:login.php');
}
Second seems like invalid syntax
Third is almost right, you just need to replace || with and or &&, as anything will be unequal to either 'user' or 'test1'

PHP can if statement have two values?

I was trying out a PHP "if" statement in which I want two things to be true: that $myvar is equal to 1 and that $myvar2 is equal to 2. However when I tried this:
if($myvar=='1', $myvar2=='2') {
header("location:index.php");
}
It failed to work. Is there a way to set up one if statement to contain these two variables like I have presented?
Thank you
You can use the boolean AND operator (&&)
if($myvar=='1' && $myvar2=='2') {
header("location:index.php");
}
Here's a full list of operators: http://php.net/manual/en/language.operators.logical.php
This will do. It is essential that you learn more about operators and flow control.
if($myvar=='1' && $myvar2=='2') {
header("location:index.php");
}
You need to use "and" operator &&
The && operator is the same as writing x='1' AND y='2',
So in ur case
if($myvar=='1' && $myvar2=='2') {
You can read more about PHP's operators at http://php.net/manual/en/language.operators.logical.php

Categories