Syntax understanding in Symfony cookbook [duplicate] - php

This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 7 years ago.
Could someone explain me the following line which is in the Symfony Cookbook (FYI the main topic is dynamic generation for Submitted Forms)
I don't undersand the following: ? , neither the array() :
$sport = $event->getData()->getSport(); // getdata submited by the user in the Sport input
$positions = null === $sport ? array() : $sport->getAvailablePositions();
// is it similaire to that line? what the difference?
$positions = $event->getData()->getSport()->getAvailablePositions();

? is a ternary if; which is an if statement on a single line.
It could be rewritten as
if (null === $sport) {
$positions = array(); // an empty array
} else {
$positions = $sport->getAvailablePositions();
}

The line says, if $sport is null (=== means check both type/value), $sport will be an empty array(), if not, $sport will be $sport->getAvailablePositions();
$positions just get the result of it!

This is called "Ternary Logic". You can check for a good article on this here: http://davidwalsh.name/php-shorthand-if-else-ternary-operators
The logic is:
Is $sport null?
If so, return an array
Otherwise, get the availablePosition collection
The goal is to have something iterable at the end and in all cases, like an array, a collection, etc.
It is not similar to $positions = $event->getData()->getSport()->getAvailablePositions(); because this will throw an error if getSport() returns null, thus calling getAvailablePosition() on something null.

It's a ternary condition operator. It's the factorisation of an if then followed by an affectation.Documentation

Related

Best practice: how to increment not existing element of array [duplicate]

This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 4 months ago.
I want to increment a value of an array, which is potentially not existing yet.
$array = [];
$array['nonExistentYet']++; // Notice
Problem
This leads to a NOTICE.
Attempt
I found a way to do this, but its kinda clunky:
$array = [];
$array['nonExistentYet'] = ($array['nonExistentYet'] ?? 0) + 1;
Question
Is there a more human readable/elegant way to do this?
well i guess a more readable way would be to use if..else as,
$arr = [];
if(array_key_exists('nonExistentYet', $arr)) {
$arr['nonExistentYet'] += 1;
}
else {
$arr['nonExistentYet'] = 1;
}
If this is used often, you can define a little helper method, which also uses an interesting side effect...
function inc(&$element) {
$element++;
}
$array = [];
inc($array['nonExistentYet']);
print_r($array);
gives...
Array
(
[nonExistentYet] => 1
)
with no warning.
As you can see the function defines the parameter as &$element, if this value doesn't exist, then it will be created, so the function call itself will create the element and then it will just increment it.
My standard implementation for this is:
if (isset($array['nonExistentYet']))
$array['nonExistentYet']++;
else
$array['nonExistentYet'] = 1;
But this is one of the rarely scenarios where I use the # operator to suppress warnings, but only if I have full control over the array:
#$array['nonExistentYet']++;
Generally, it is not good to suppress warnings or error messages!
What you ask is a little vague,
Either the variable exists and you increment it, or it does not exist in this case you create it.
In another case suppose that you want to do it in a for loop, in this case you do not have to worry about the existence of the variable.
One way is ternary operator, which checks if array value exists:
$array['iDoNotExistYet'] = empty($array['iDoNotExistYet']) ? 1 : ++$array['iDoNotExistYet'];
Other one would be just rewriting it to if and else condition.

PHP why (null === $variable) and not ($variable === null) in comparison? [duplicate]

This question already has answers here:
Is there any benefit of using null first in PHP?
(5 answers)
Closed 8 years ago.
When reading Symfony2 code I came across this comparaison many times
if (null === $variable ) { ... }
I use
if ($variable === null ){ ... }
because I see it more readable.
Is there a wisdom behind using the first notation ?
No compile/interpretting difference at all, it's pure code style.
It's also known as Yoda Conditions.
It helps prevent accidental assignments:
if ($foo = null) { ... }
would not cause a parse error, while will
if (null = $foo) { ... }
1st example: http://sandbox.onlinephpfunctions.com/code/fff14c285a18a7972a3222ff5af08da825760c10
2nd example: http://sandbox.onlinephpfunctions.com/code/118d494c17381d8e129ba005465bf84d9b8819bd
Not only does it help prevent accidental assignments, but also avoids confusion when we do intentionally want to make an assignment when evaluating a condition.
if (null !== $article = $repository->findOneById($request->query->get('id'))) {
$title = $article->getTitle();
//....
}

Just need to understand a PHP Syntax used to set POSTed var [duplicate]

This question already has answers here:
What is ?: in PHP 5.3? [duplicate]
(3 answers)
Closed 8 years ago.
So I'm using the following php code to set variables that are received from a POST method, but I'm interested in how it works.
$var1 = isset($_REQUEST['var1']) ? $_REQUEST['var1'] : 'default';
I understand what it does, but I don't understand the syntax.
Thanks for the help :)
? is just a short and optimised notation of doing this:
if (isset($_REQUEST["var1"])) // If the element "var1" exists in the $_REQUEST array
$var1 = $_REQUEST["var1"]; // take the value of it
else
$var1 = "default"; // if it doesn't exist, use a default value
Note that you might want to use the $_POST array instead of the $_REQUEST array.
This is a short hand IF statement and from that you are assigning a value to $var1
The syntax is :
$var = (CONDITION) ? (VALUE IF TRUE) : (VALUE IF FALSE);
You probably mean ternary operator
Syntax it's same like
if(isset($_REQUEST('var1') ) {
$var1 = ? $_REQUEST('var1')
}else {
$var1 =: 'default';
}
It's the synatx of the ternary operator. It's shorthand for if/else. Please read PHP Manaul
This is a 'ternary operator', what it says is:-
If var1 is set as a post variable then set var1 to that value, otherwise setvar1 to be the string 'default'. Using traditional syntax it would be:-
if (isset($_REQUEST('var1')) { $var1 = $_REQUEST('var1'); } else { $var1 = 'default'; }
its a short way of doing an if. if you are expecting a post variable its must better to use _POST rather than request.
the "?" says if the isset($_REQUEST) is true, then do the everything between the ? and : otherwise do everything between the : and the ;

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.

What does ? ... : ... do? [duplicate]

This question already has answers here:
What are the PHP operators "?" and ":" called and what do they do?
(10 answers)
Closed 5 years ago.
$items = (isset($_POST['items'])) ? $_POST['items'] : array();
I don't understand the last snippet of this code "? $_POST['items'] : array();"
What does that combination of code do exactly?
I use it to take in a bunch of values from html text boxes and store it into a session array. But the problem is, if I attempt to resubmit the data in text boxes the new array session overwrites the old session array completely blank spaces and all.
I only want to overwrite places in the array that already have values. If the user decides to fill out only a few text boxes I don't want the previous session array data to be overwritten by blank spaces (from the blank text boxes).
I'm thinking the above code is the problem, but I'm not sure how it works. Enlighten me please.
This is a ternary operator:
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
That last part is known as the conditional operator. Basically it is a condensed if/else statement.
It works like this:
$items =
// if this expression is true
(isset($_POST['items']))
// then "$_POST['items']" is assigned to $items
? $_POST['items']
// else "array()" is assigned
: array();
Also here is some pseudo-code that may be simpler:
$items = (condition) ? value_if_condition_true : value_if_condition_false;
Edit: Here is a quick, pedantic side-note: The PHP documentation calls this operator a ternary operator. While the conditional operator is technically a ternary operator (that is, an operator with 3 operands) it is a misnomer (and rather presumptive) to call it the ternary operator.
It is the same as:
if (isset($_POST['items']){
$items = $_POST['items'];
} else {
$items = array();
}
Look at Paolo's answer to understand the ternary operator.
To do what you are looking at doing you might want to use a session variable.
At the top of your page put this (because you can't output anything to the page before you start a session. I.E. NO ECHO STATEMENTS)
session_start();
Then when a user submits your form, save the result in this server variable. If this is the first time the user submitted the form, just save it directly, otherwise cycle through and add any value that is not empty. See if this is what you are looking for:
HTML CODE (testform.html):
<html>
<body>
<form name="someForm" action="process.php" method="POST">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input name="items[]" type="text">
<input type="submit">
</form>
</body>
</html>
Processing code (process.php):
<?php
session_start();
if(!$_SESSION['items']) {
// If this is the first time the user submitted the form,
// set what they put in to the master list which is $_SESSION['items'].
$_SESSION['items'] = $_POST['items'];
}
else {
// If the user has submitted items before...
// Then we want to replace any fields they changed with the changed value
// and leave the blank ones with what they previously gave us.
foreach ($_POST['items'] as $key => $value) {
if ($value != '') { // So long as the field is not blank
$_SESSION['items'][$key] = $value;
}
}
}
// Displaying the array.
foreach ($_SESSION['items'] as $k => $v) {
echo $v,'<br>';
}
?>
yup... it is ternary operator
a simple and clear explanation provided here, in which the author said it is like answering : “Well, is it true?”
the colon separates two possible values (or). the first value will be chosen if the test expression is true. the second (behind the colon) will be chosen if the first answers is false.
ternary operator very helpfull in creating variable in php 7.x, free of notice warning. For example"
$mod = isset($_REQUEST['mod']) ? $_REQUEST['mod'] : "";
Basically if $_POST['items'] exists then $items gets set to it otherwise it gets set to an empty array.
It is a ternary operator that essentially says if the items key is in the $_POST then set $items to equal the value of $_POST['items'] else set it to a null array.
I figured it's also worth noting that ?: is a separate operator, where:
$one = $two ?: $three;
$one = two() ?: three();
is shorthand for:
$one = $two ? $two : $three;
$one = two() ? two() : three();
Aside from typing less, the runtime advantage is that, if using a function like two(), the function would only be evaluated once using the shorthand form, but possibly twice using the long form.

Categories