PHP - ternary for undefined index - php

I have a PHP error notice:
Undefined index: inventory_amount
$chains[$key] = intval($chain_product['inventory_amount']);
Is it possible to fix it in one line like with ternary function and not with:
if(!empty($chain_product['inventory_amount'])) {
$chains[$key] = intval($chain_product['inventory_amount']);
}
New with PHP. Thanks

Yes, PHP has ternary operator.
Like this:
$variable = ( condition ? true : false );
So in your case it like this:
$chains[$key] = ( !empty($chain_product['inventory_amount']) ? intval($chain_product['inventory_amount']) : 0 );
so if you have inventory_amount empty, it will have 0 assigned as a "fallback".

Related

PHP - Undefined index solving returns warining

I have a function within my PHP project which has some specific params..
$user_sequence = $user['user_sequence'];
if ($cached || !$user_sequence) {
return;
}
Notice: Undefined index: user_sequence
I have fixed that with:
if (isset($user['user_sequence'])) {
$user_sequence = $user['user_sequence'];
}
But now my second if() clause get's a warning:
Variable '$user_sequence' is probably undefined
Would setting it to null before if() be the best approach to solve it? Thanks
Spelled out in full, you need to specify what the value should be if $user['user_sequence'] is not set. In your second if statement, you are checking !$user_sequence, so a logical default value would be boolean false:
if (isset($user['user_sequence'])) {
$user_sequence = $user['user_sequence'];
}
else {
$user_sequence = false;
}
Luckily, PHP doesn't make use write out that whole if statement, because we can use the null coalescing operator, and shorten it to this:
$user_sequence = $user['user_sequence'] ?? false;
In other situations, you might want to default to an empty array ($something ?? []) or even just null ($something ?? null).

What means this line? [duplicate]

This question already has answers here:
How to replace "if" statement with a ternary operator ( ? : )?
(16 answers)
Closed 3 years ago.
$n = isset($_GET["n"]) ? $_GET['n'] : '';
I find this "method" to avoid errors before insert stuff in the input type.. and it works.. but I would like a detailed explanation of this line. Thank you!
This is called the ternary operator shorthand of if...else
(condition) ? true : false
There is a condition which has been checked on left, if its true the statement after the ? will be execute else the statement after the : will execute.
It's called Ternary operator
The ternary operator is a shorthand for the if {} else {} structure. Instead of writing this:
if ($condition) {
$result = 'foo'
} else {
$result = 'bar'
}
You can write this:
$result = $condition ? 'foo' : 'bar';
If this $condition evaluates to true, the lefthand operand will be assigned to $result. If the condition evaluates to false, the righthand will be used.
In your case
If the value of $_GET["n"] isset then it'll take $_GET["n"] value.
if the value is not set then it'll take ('') value.
$n = isset($_GET["n"]) ? $_GET['n'] : '';

getopt -> return PHP Notice: Undefined index:

I'm using getopt to pass variables to my script, but I get the message:
PHP Notice: Undefined index:
Here's my code:
$MyOptions = getopt("c:hp:");
if ($MyOptions['c']) { //line wher error show up!
$MyClub = $MyOptions['c'];
} else {
$MyClub = '53';
}
What did I miss?
The problem is the index c in your $MyOptions array does not exist, you can avoid this in a number of ways, but my preferred option in this case would be to replace the entire if-else statement with;
$MyClub = $MyOptions['c'] ?? '53';
The ?? is the Null Coalescing operator.
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
Please be aware this is only available from PHP 7, otherwise you will have to use an isset() to check if the index exists.

Drupal 7 - Notice: Undefined index: und in include()

I'm getting this error:
Notice: Undefined index: und in include() (line 24 of /home/cliffdwellerproductions/dev.cliffdwellerdigital.com/Dahl/sites/all/themes/basic/templates/node--page2.tpl.php).
the code is:
if ($node->field_body_left !== NULL) :
$text = trim($node->field_body_left['und']['0']['value']);
else:
$text = '';
Please help, as I haven't been able to define the variable...
Alf
Your $node->field_body_left variable is existent but it doesn't have an 'und' element.
It looks like you're attempting to check for an empty field, but you're using $field_body_left!==null which will only be false if the variable is literally null. When a drupal field is present but empty, it's usually equal to array(). Use != instead of !==, and then it will correctly detect both null variables and empty arrays and move on.
--
Extra info: If the variable had a value, its structure would be:
$field_body_left = array(
'und' => array(
0 => array (
'value' => YOURVALUE
)
)
)
But since it doesn't have a value, its structure is:
$field_body_left = array()

Using nested ternary operators [duplicate]

This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I've been trying to use isset() in nested form like below:
isset($_POST['selectedTemplate'])?$_POST['selectedTemplate']:isset($_GET['selectedTemplate'])?$_GET['selectedTemplate']:0
But seems I'm missing something. Can anyone assist me how to do it?
Wrap it in parentheses:
$selectedTemplate = isset($_POST['selectedTemplate'])
? $_POST['selectedTemplate']
: (
isset($_GET['selectedTemplate'])
? $_GET['selectedTemplate']
: 0
);
Or even better, use a proper if/else statement (for maintainability):
$selectTemplate = 0;
if (isset($_POST['selectedTemplate'])) {
$selectTemplate = $_POST['selectedTemplate'];
} elseif (isset($_GET['selectedTemplate'])) {
$selectTemplate = $_GET['selectedTemplate'];
}
However, as others have pointed out: it would simply be easier for you to use $_REQUEST:
$selectedTemplate = isset($_REQUEST['selectedTemplate'])
? $_REQUEST['selectedTemplate']
: 0;
As of PHP 7 we can use Null coalescing operator
$selectedTemplate = $_POST['selectedTemplate'] ?? $_GET['selectedTemplate'] ?? 0;
A little investigate here, and I guess, I've found real answer :)
Example code:
<?php
$test = array();
$test['a'] = "value";
var_dump(
isset($test['a'])
? $test['a']
: isset($test['b'])
? $test['b']
: "default"
);
Be attentive to round brackets, that I've put.
I guess, you're waiting to get similar behavior:
var_dump(
isset($test['a'])
? $test['a']
: (isset($test['b']) // <-- here
? $test['b']
: "default") // <-- and here
);
But! Real behavior looks like this:
var_dump(
(isset($test['a']) // <-- here
? $test['a']
: isset($test['b'])) // <-- and here
? $test['b']
: "default"
);
General mistake was, that you've missed notice: Undefined index.
Online shell.
It's simpler to read if we write ternary in the following manner:
$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');
But ternary operators are short, effective ways to write simple if statements. They are not built for nesting. :)
You might have an easier time simply using the $_REQUEST variables:
"$_REQUEST is an associative array that by default contains the contents of $_GET, $_POST and $_COOKIE."
http://us2.php.net/manual/en/reserved.variables.request.php
I believe this will work:
$test = array();
$test['a'] = 123;
$test['b'] = NULL;
$var = (isset($test['a']) ? $test['a'] : (!isnull($test['b']) ? $test['b'] : "default"));
echo $var;
Instead of the ternary with the ambiguous precedence, you could just use $_REQUEST instead of the fiddly $_GET and $_POST probing:
isset($_REQUEST['selectedTemplate']) ? $_REQUEST['selectedTemplate'] : 0
This is precisely what it is for.

Categories