PHP equivalent of a Ruby assignment idiom [duplicate] - php

This question already has answers here:
Setting default values (conditional assignment)
(6 answers)
Closed 4 years ago.
what's the PHP equivalent of Ruby's "||=" assignment idiom?
The scenario is I want to instantiate an object or array "on demand," and not necessarily when a class is initialized.
I've tried to find this in the PHP docs, but I'm having difficulty finding things I need in there (miss the Ruby).
Thank you!

I don't think PHP has a similar assignment syntax. You'll have to fake it with something like this:
if (empty($someVar)) $someVar = "DefaultVal";
Note: I'm not familiar with Ruby, so I read up on the ||= operator here. I'm not sure how that operator, as explained at that link, would help you do what you want either, but whatever.

What about:
<?php $someVar ?: 'default value'; ?>
This works well with PHP 5.3.

The answer is right but if the value does not exist it will raise an E_NOTICE. For example for $_GET['key']. If key is not in the array of $_GET it will raise an E_NOTICE.
If you are working with PHP 7 (which I totally recommend to use) there's a new feature called Null Coalesce Operator.
This way it returns the result of its first operand if it exists and is not NULL, or else its second operand:
<?php $foo = $foo ?? 'default value'; ?>

This is one of those things I miss from Ruby. You can also do:
$foo = empty($foo) ? "default" : $foo;
Ugly as hell though.

Related

Check method in method exists or is not null [duplicate]

This question already has answers here:
Is there a "nullsafe operator" in PHP?
(3 answers)
Closed 1 year ago.
Is there a better way to check all this in less lines of code?
if (
$item->getProduct() !== null
&& $item->getProduct()->getMedia() !== null
&& $item->getProduct()->getMedia()->count()
&& $item->getProduct()->getMedia()->first() !== null
&& $item->getProduct()->getMedia()->first()->getMedia()
) {
$imageUrl = $item->getProduct()->getMedia()->first()->getMedia()->getUrl();
In PHP 8.0, there is a new "nullsafe operator", spelled ?-> for exactly this purpose: it calls the method only if the value is not null.
The only part if can't do is the extra check on ->count(), but as long as ->first() returns null rather than an error on an empty set, this would work:
$imageUrl = $item?->getProduct()?->getMedia()?->first()?->getMedia()?->getUrl();
Unless and until you can upgrade to PHP 8, your best bet will be to look for ways to improve the API to avoid this problem in the first place. In line with the Law of Demeter, you could define additional methods so that you could write this:
$imageUrl = $item->hasProductMedia() ? $item->getProductMedia()->first()->getUrl() : null;
The implementation of hasProductMedia() and getProductMedia() still need those checks, but they're hidden away rather than written each time you need to access it.
Another approach is the "Null Object Pattern" (hat tip to Markus Zeller for mentioning this in comments). Instead of returning null, each method returns a special "empty object" satisfying the correct interface.
So $item->getProduct() would never return null, but might return a NullProduct; calling getMedia() on that, or any product without any media, would return an EmptyMediaList; and so on. Eventually, you'd call getUrl() on a NullMediaItem, and it would give you a null value.

PHP "Ternary Like" Boolean Expression Curiosity [duplicate]

This question already has answers here:
Short-circuit evaluation via the AND operator in PHP
(5 answers)
Closed 6 years ago.
This is just more of a "why does it work" and "why or why not use it" type question.
We all know PHP expressions using ternary operations
$var = (isset($i) ? true:false);
But in PHP something like the following works too. (It is not ternary, 3 parts, it is more of a binary operation, 2parts.)
$var = true;
isset($i) || $var = false;
Which may not be so practical :) but a more useful construction is
isset($i) || exit();
So the above (much better looking imo) would have the same result as
if(!isset($i)) exit();
But other than the common
defined('CONSTANT') || define('CONSTANT','FOO');
I rarely see this type of construct used in PHP. Why does this work? What is it called. Why is it not taught or used more. Are there cons to using it? And is there practical ways to use && in the same way?
This way of writing statements also exists in C, Perl and other languages, it plays with how the compiler evaluates statements chained with logical operators.
Imagine you have an expression if (a() or b()), then when a() returns true you don't have to evaluate b(), because the entire statement is true already. So b() is only called when a() is false. You can write this without the if, it still works the same way.
This shorthand is usually found like you described, to define default values or exit if a condition is not met.

Using an array without initialization in PHP [duplicate]

This question already has answers here:
Should an array be declared before using it? [closed]
(7 answers)
Closed 7 years ago.
In most languages, I have to initialize an associative array before I can use it:
data = {}
data["foo"] = "bar"
But in PHP I can just do
data["foo"] = "bar"
Are there any repercussions to doing this? Is this "the right way" to write PHP?
Is the same, but is not a good idea, the next is a copy-paste from php documentation.
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.
Basically it's the same, and no you won't find any problem or repercussion.
But if you like you can do this:
$a = array();
You can read more in the PHP page

Increasing not initialize array value in php [duplicate]

This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 5 months ago.
Hy
I have a foreach loop that adds array keys to another array. I wanted to know if it' safe to increment (with ++) and uninitialize element.
At the moment my code is:
foreach($SociBdP as $id=>$socio)
{
if(!isset($provenienza[$option_name]))
$provenienza[$option_name]=0;
$provenienza[$option_name]++;
}
I wanted to know if it's safe to do
foreach($SociBdP as $id=>$socio)
{
$provenienza[$option_name]++;
}
or if there is a risk (like in c++) that the default value of the array isn't 0
While it's a documented behaviour you can trust:
It is not necessary to initialize variables in PHP however it is a
very good practice. Uninitialized variables have a default value of
their type depending on the context in which they are used - booleans
default to FALSE, integers and floats default to zero, strings (e.g.
used in echo) are set as an empty string and arrays become to an empty
array.
... it also prevents you from taking benefit of notices since you need to lower down your error reporting settings so they don't show up in the development phase:
var_dump($foo);
Notice: Undefined variable: foo in D:\tmp\borrame.php on line 3
NULL
Notices are often seen as an annoyance by newbies but they're actually a terrific tool to spot silly typos.
In PHP 7, we can use the "null coalescing operator" (??) :
$provenienza[$option_name] = ($provenienza[$option_name] ?? 0) + 1;
It is much simpler and with less "repetition" than using isset()
Nope, the correct one is:
foreach($SociBdP as $id=>$socio)
{
if(!isset($provenienza[$option_name]))
$provenienza[$option_name]=0;
$provenienza[$option_name]++;
}
You have to be sure that the array contains the key before you increment it.

checking for null and assigning in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Where can I read about conditionals done with ? and :
I want do the following without using if else or a ternary operator:
if $_GET['a'] is not null then set $a= $_GET['a'] else set its value to "default".
I tried $a= $_GET['a'] || "default". but it doesnt work.
I remember seeing something like this in a code sample, but I can't recall now.
I think a ternary if is your best bet here.
In this case I would use isset check - to determine if the key is set and is not null:
$a = isset($_GET['a']) ? $_GET['a'] : "default"
The or operator || doesn't work to null coalesce like that in PHP, but you might have seen it in JavaScript where it can be used to set a value to the first non-false result:
e.g
var a = get['a'] || 'default';
Refer this PHP shorthand if/else (ternary) information in http://davidwalsh.name/php-ternary-examples
and also
http://davidwalsh.name/learning-ternary-operators-tips-tricks
Well, people here doesn't seem to bother reading the entire question this late.
That sintax you wrote works on some other languages but apparently not on php. I think you should just stick to the ternary operator or write a function for that as a shortcut if you're going to use this kind of verification a lot on your page.
function GET($v, $default)
{
return !isset($_GET[$v]) || empty($_GET[$v]) ? $default : $_GET[$v];
}
$a = GET("a", "default");

Categories