Testing variables in PHP - php

Earlier today I tried to do this:
Example 1:
<?php
echo $myVar || "rawr";
?>
I thought this might print out $myVar if it was set, and print "rawr" if not.
It printed a 1, I assume this is the result of the OR test.
What I then tried was this:
Example 2:
<?php
if ($myVar)
{
echo $myVar;
}
else
{
echo "rawr";
}
?>
Which is what I was trying to accomplish.
I think I understand why the first prints the results of the OR test rather than one of the variables, and also why I tried it - been spending some time on the bash shell recently :)
Can anyone tell me if there is a way to perform the text in example #2 but in similar syntax to example #1?

PHP 5.3:
echo $myVar ?: 'rawr';
Pre 5.3:
echo $myVar ? $myVar : 'rawr';
If $myVar may not be set you'd have to use isset($myVar) and $myVar as the condition (which then wouldn't work with the shorthand ?: syntax, as this would echo 1 if it was set, rather than the value).
echo (isset($myVar) and $myVar) ? $myVar : 'rawr';

PHP is notoriously inelegant in this department, and there really is no good way of making this test.
As a general solution, you 'd need to use the ternary operator as in empty($var) ? "rawr" : $var. However, in practice what happens is that you have one of two scenarios:
1. Your own variable
In this case where you define the variable yourself, the best solution is to just give it a known default value at the place you define it (possibly with the ternary operator).
2. Inside an array
If the array is one that should not be touched like one of the superglobals, then you can wrap the test inside a function (pretty much that's what everyone does).
If the array is one under your jurisdiction but it comes from an external source, you can use the "add the defaults" trick:
$incoming = array(...);
$defaults = array("foo" => "bar");
// Inject the defaults into $incoming without overwriting existing values
$incoming += $defaults;
At this point you know for a fact that every key inside $defaults also exists inside $incoming.

In PHP 5.3+ it is possible to leave out the second argument:
echo $myVar ?: 'rawr';
This is probably closest to what you want.

Try this:
echo $myVar = ($myVar) ? $myVar : 'rawr';
or
echo $myVar ? $myVar : 'rawr';

I think you want to use something like var_dump($varname) or isset($varname) ?

it's matter of operator precedence. you can't do that.
two points as a food for thought
if $myVar is not set, you'll get an error message, not "wawr";
by the time you're going to echo some variables, every one of them should be defined and have value. That will make your template clean and readable.

Try
echo ($myVar != null ? $myVar : "Rawr!");

Related

PHP Multiple actions in true clause in shorthand IF

Pretty sure there's a simple answer to this but difficult to search on because of the vague terms used.
I'm using shorthand if statements and want to do more than one action when it returns true, what does the syntax look like?
For example, logically thinking I tried something like:
<?php
$var = "whatever";
(isset($var) ? $var2=$var; $var3=$var : $error="fubar");
?>
Obviously this stops with unexpected ; but hopefully you get the idea of what I'm trying to accomplish.
So sorry if this is a duplicate question, I swear I searched for it. :)
Thanks!
EDIT
I understand that whether or not shorthand is appropriate for this situation should be questioned. But still, can it be done, is the question.
Yes it's possible by using && between each assignment:
(isset($var) ? ($var2=$var) && ($var3=$var) : $error="fubar");
In the above code, if $var is set, $var2 and $var3 will get the same value, otherwise the two variables will not be changed.
That said, it is not the most appropriate method. The ternary operator should be used for simple logic, when the logic starts to get complicated, ternary is most likely no longer the best option. Instead you should just use a simple if/else.
For this specific instance, you can do this:
In this specific instance you can use this:
$output = (isset($var)) ? $var2 = $var3 = $var : false;
Slightly better option for this specific test instance:
$error = (isset($var)) ? !(bool)($var2 = $var3 = $var) : true;
This will set $error to true IF $var is not set, and to false if $var is set, so you could follow this up with an if($error) block.
However, ternary probably isn't the best way to approach this...
For more complicated instances you'd need to use closures or, worse, predeclared functions:
$output = (isset($var)) ? setVars($var) : false;
function setVars($var) {
$var2 = $var3 = $var;
}
At this point, you're probably better off with if or switch statements.
As far as I know, it is not possible, and shouldn't be possible. (?:) is not, and should not be taken as a if, because it doesn't works the same way, and is not designed for it.
The ternary operator exist as a way to return a value depending of a condition, not as a "quick" if.
If you are using it without needing the return value, then you probably are using it wrong.
In this specific case, you should be using and if-else statement. It would also help making your code more readable.

Echo defined constant depending on variable without if() in PHP

The title might be a bit confusing, but w/e.
Is it possible to do something like this?
define('test_1', 'test1');
define('test_2', 'test2');
define('test_3', 'test3');
$test='2';
echo test_$test;
I simply want to echo one of those defined constants (in this case 2) depending on what $test is, without using if() or switch().
You should be sorted with the following:
echo constant('test_'.$test);

Is is possible to call a variable that has been assigned after the call (PHP)?

The title is in the question (EDIT: :P I mean the question is in the title), basically can I call variable $x before defining it further down the page?
Short answer, no.
Long answer, noooooooooooooooooooooooooooooooooooooooooo.
But seriously, you can refer to it, it just won't do what you want.
Depending on how strict your warnings on you can call an undeclared variable as much as you want. However until you assign it a value it won't have a value.
I am not quite sure to understand your point but if you want to write
echo $x;
$x = "2";
you will not get "2" as a result.
PHP will usually not issue a warning when you reference a variable that has not yet been assigned a value. PHP will create it on the fly and assign it the null value which will then be casted to whatever scope you have. For example
$a = $b + 5;
echo $a;
will print 5 because in this case $b will be interpreted as beeing 0.
I hope this will help
Jerome
No, the execution goes down the file. You can use a function though, to call later on once the variable has been defined. For example:
<?php
function meow() {
echo $kitty_noise;
}
?>
And then later on down the file...
<?php
$kitty_noice = 'meowwwwww!';
meow();
?>
Horrible example....

Most efficient php if structure

What runs faster?
Setting a default value and changing it-
$foo = "";
if($bar)
{
$foo = "someValue";
}
Or-
if($bar)
{
$foo = "someValue";
}
else
{
$foo = "";
}
You absolutely should not be bothered with performance of a single if statement.
Also, consider:
$foo = $bar ? "" : "someValue"
At a guess, the 2nd one "potentially". First one you're potentially setting 2 values. Second one you're definitely only setting one.
Its also a question though of code clarity. If you've got 2 alternatives (e.g turn left or right) then use the "else" statement. If you've got a 'normal' value vs a flag e.g http or https, then use the first one
EDIT: becose you valorize a variable in base to another one, the isset() statement is mandatory.. so the 'faster one' is the second way becose, as David said, yoo valorize the $foo var just one time.
Also consider the Anton suggestion to use the short if syntax (dont know if it speed up the execution)
P.s: if your goal is to speed up many if like that one, use the ' instead of ", becose the content inside "" is being evalutated by php (in case it contain a variable:

Conditional operator with only true statement

I want to set a variable to a value, but only if a condition is true.
Instead of doing the following:
if($myarray["foo"]==$bar){
$variablename=$myarray["foo"];
}
This can end up being quite long if the variable names are long, or perhaps it involves arrays, when it's quite simple what I want to do — set a value if a condition is true.
I would like to use the conditional operator, something like this:
$variablename=($myarray["foo"]=="bar")? $myarray["foo"]......
But this fails because I don't want the variable to be set at all if the statement is false.
Basically, what I'm trying to do is make the first example shorter. Perhaps the conditional operator is not the way though...
Does anyone have any suggestions?
It doesn't get much shorter than:
if($condition) $var = $value;
IMO, the best way to make your code sample shorter is:
if($myarray["foo"] == $bar)
$variablename = $myarray["foo"];
FYI, the name of the operator you're asking about isn't "the ternary operator", it's the conditional operator.
Since you ask, a way you could actually use the conditional operator to do what you're asking is:
$myarray['foo'] == $bar ? $variablename = $myarray['foo'] : null;
but that's somewhat horrifically ugly and very unmaintainable.
You could do this, but I wouldn't as it is pretty unreadable and stupid:
$myarray["foo"] == $bar ? $variablename = $myarray["foo"] : 0;
or
$myarray["foo"] == $bar && $variablename = $myarray["foo"];
Your right, ternary is not the way to go. It's there to handle the if and else part of the statement.
Just stick with the regular if statement.
if($myarray["foo"]==$bar) $variablename=$myarray["foo"];
The "problem" you have isn't really a problem. Your example code is very clear and maintainable. I would really say leave it like it is.
You -could- remove the braces, but that will have an impact on maintainability.
Your other alternative is to create a set_if_true(mixed array, string key, boolean conditional) wrapper function. It hides what is really happening but depending on your specific implementation it is a good option. (For instance a configuration type object, or caching backend)
Put != instead of == and ?: instead of just ?..
$variablename = ($myarray["foo"] != "bar") ?: $myarray["foo"];
is the same as
if($myarray["foo"] != "bar"){} else { $variablename = $myarray["foo"]; }
It might not be the smartest solution but it works. I like this one more
if($myarray["foo"] != "bar") {$variablename = $myarray["foo"]};
Set the variable to itself in the false case:
$variablename=($myarray["foo"]=="bar")? $myarray["foo"] : $variablename
You can put the original expression in the else part of the ternary operation, but if you want to guarantee single evaluation of the expression then you'll have to use a temporary variable and an if statement.
Ternary isn't the way, even though it can be written so that ternary works.
The reason is this: you're trying to use it in a way it's not intended, which will make your code awkward for other developers to read.

Categories