Normal expression works fine, shorthand doesn't. Where am I wrong here?
if (isset($var)) $value = $var;
elseif ($str !== 'string') $value = $str;
else $value = null;
// works just fine
$value = (isset($var)) ? $var : ($str !== 'string') ? $str : null;
// only returns $value = $str
Thanks
Try with an extra set of brackets around the second shorthand block, $value = (isset($var)) ? $var : (($str !== 'string') ? $str : null);
Added this side note...
While it's fun trying to squeeze code into one line, it is often better to write it out so that it's easy to read. Your line of code is compact but takes a while to digest whereas...
if (isset($var)) {
$value = $var;
}
else if ($str !== 'string') {
$value = $str;
}
else {
$value = null;
}
... makes it very clear what's going on - you'll thank yourself in a few months when you look back at your code :)
Related
How to replace this :
if( $this->getInfo() ){
$value = $this->getInfo();
}else{
$value = $this->getAnotherInfo();
}
This would be nicer solution :
$value = $this->getInfo() ? $this->getInfo() : $this->getAnotherInfo();
But we repeat $this->getInfo().
Here is the fun:
$value = $this->getInfo() ? : $this->getAnotherInfo();
If it bothers you having to repeat the expression you could write a function that returns the first truthy value.
$value = which ($this->getInfo(), $this->getAnotherInfo());
function which () {
if (func_num_args()<1) return false;
foreach (func_get_args() as $s) if ($s) return $s;
return false;
}
A nasty option would be this:
if (!($value = $this->getInfo())) $value = $this->getOtherInfo();
If the assignment returns false assign the other value.
But aside from this looking disgusting, it is still repetitive, albeit in a different way.
As of PHP 5.3, you can leave out the middle part of the ternary operator and avoid the repetition:
$value = $this->getInfo() ? : $this->getOtherInfo();
Which does what you want.
Is it possible to convert null to string with php?
For instance,
$string = null;
to
$string = "null";
in PHP 7 you can use Null coalescing operator ??
$string = $string ?? 'null';
Am I missing something here?
if ($string === null) {
$string = 'null';
}
was thinking something shorter...
You can do it in one line, and omit the braces:
if ($string === null) $string = 'null';
You can also use the conditional operator:
$string = ($string === null) ? 'null' : $string;
Your call.
var_export can represent any variable in parseable string.
While not very elegant or legible, you can also do the following
is_null($string) && $string = 'null'; // assignment, not a '==' comparison
// $string is 'null'
or
$string = is_null($string) ? gettype($string) : $string;
// $string is 'NULL'
Note: var_export($string, true) (mentioned in other replies) returns 'NULL'
if ($string === null)
{
$string = "null";
}
it has best solution:
$var = null;
$stringNull = json_encode($var);
$null = json_decode($stringNull, true);
var_dump($stringNull);
var_dump($null);
I want to change the variable being assigned based on condition, and I can seem to get it working.
$condition = false;
($condition !== false ? $array[1][$condition] : $array[1]) = 'Test';
In this example, if $condition isn't false, I want to assign the string "Test" to $array[1][$condition]. Otherwise, assign it to $array[1]
I can easily do this like this:
if ($condition !== false) {
$array[1][$condition] = 'Test'; }
else {
$array[1] = 'Test'; }
But due to the nature of the code this can get quite cluttered, which is why I wish for it to be an inline conditional statement.
Thanks for any help!
$condition = false;
$array[1][$condition] = ($condition !== false ? 'Test' : $array[1]);
$condition !== false ? $array[1][$condition] = "Test" : $array[1] = "Test";
The result of the ternary operator is not a reference, so you can't use it as the left-hand side of an assignment.
You might be able to use variable variables and references, but this might just add complexity without providing any real benefit.
Something like this:
$a =& $array[1];
$b =& $array[1][$condition];
$var = ($condition !== false ? 'b' : 'a');
$$var = 'Test';
I have a variable$var.
I want echo "true" if $var is equal to any of the following values abc, def, hij, klm, or nop. Is there a way to do this with a single statement like &&??
An elegant way is building an array on the fly and using in_array():
if (in_array($var, array("abc", "def", "ghi")))
The switch statement is also an alternative:
switch ($var) {
case "abc":
case "def":
case "hij":
echo "yes";
break;
default:
echo "no";
}
if($var == "abc" || $var == "def" || ...)
{
echo "true";
}
Using "Or" instead of "And" would help here, i think
you can use in_array function of php
$array=array('abc', 'def', 'hij', 'klm', 'nop');
if (in_array($val,$array))
{
echo 'Value found';
}
Dont know, why you want to use &&. Theres an easier solution
echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop'))
? 'yes'
: 'no';
you can use the boolean operator or: ||
if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){
echo "true";
}
You can try this:
<?php
echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>
I found this method worked for me:
$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
echo "Product found";
}
Sorry to resurrect this, but I stumbled across it & believe it adds value to the question.
In PHP 8.0.0^ you can now use the match expression like so:
<?php
echo match ($var) {
'abc','def','hij','klm' => 'true',
};
?>
//echos 'true' as a string
Working link from OnlinePHPfunctions
PHP Manual
Try this piece of code:
$first = $string[0];
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
$v='starts with vowel';
}
else {
$v='does not start with vowel';
}
It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.
$test_array = ('test1','test2', 'test3','test4');
for($i = 0; $i < count($test_array); $i++){
if($test_value == $test_array[$i]){
$ret_val = true;
break;
}
else{
$ret_val = false;
}
}
I don't know if $var is a string and you want to find only those expressions but here it goes either way.
Try to use preg_match http://php.net/manual/en/function.preg-match.php
if(preg_match('abc', $val) || preg_match('def', $val) || ...)
echo "true"
Is there a better way to do this simple task below? Like with an array or even another method?
<?PHP
// current way
if ($city != NULL) {
$city = FilterALLHTML($city);
}
if ($state != NULL) {
$state = FilterALLHTML($state);
}
if ($title != NULL) {
$title = FilterALLHTML($title);
}
if ($division != NULL) {
$division = FilterALLHTML($division);
}
?>
Here is my current function
function FilterALLHTML($document) {
//old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html
$text = strip_tags($document);
$search = array ("/f.?u.?c.?k/i",
"/(s|$).?h.?i.?t/i",
'/(potspace|mycrib|palbolt)/i');
$text = preg_replace ($search, '', $text);
return $text;
}
UPDATE - Ok my new function after the suggestions from this post thanks guys
function FilterALLHTML($var) {
//old array line //"'<[\/\!]*?[^<>]*//?//>'si",// strip html
if ($var != null){
$text = strip_tags($var);
$search = array ("/f.?u.?c.?k/i",
"/(s|$).?h.?i.?t/i",
'/(potspace|mycrib|palbolt|pot space)/i');
$text = preg_replace ($search, '', $text);
return $text;
}
return null;
}
Change your FilterALLHTML function to do the null check and have it return null?
Then you can throw away all the ifs.
Example:
function FilterALLHTML($input)
{
if ($input === null)
return null;
// Original code, I'll just use strip_tags() for a functional example
return strip_tags($input);
}
Edit:
I felt like sharing an alternative to variable variables, as I don't really like the idea of using string literals instead of variable names. References all the way :)
function FilterALLHTML(&$text)
{
if ($text !== null)
{
// Omitted regex bit for simplicity
$text = strip_tags($text);
}
}
$city = "<b>New York</b>";
$state = null;
$title = "<i>Mr.</i>";
$fields = array(&$city, &$state, &$title);
foreach ($fields as &$var)
FilterALLHTML($var);
(note: FilterALLHTML implementation differs from first example)
Yes, use PHP's variable variables.
$vars = array('city','state','title','division');
foreach($vars as $v) {
if ($$v != null) $$v = FilterAllHTML($$v);
}
If you know for a fact that all the variables have been previously defined, then you don't need the null check. Otherwise, the null check will prevent E_NOTICE errors from triggering.
foreach (array('city', 'state', 'title', 'division') as $var) {
if ($$var != null) {
$$var = FilterALLHTML($$var);
}
}
Like Thorarin I'd suggest having your FilterALLHTML function check for null instead though.
zombat's answer is the best, but I'd add that you shouldn't really be checking for null either. If for some reason FilterAllHTML has a problem with null values, which it shouldn't, put the check for null in the FilterAllHTML function definition.
$vars = array('city', 'state', 'title', 'division');
foreach($vars as $var) {
$$var = FilterAllHTML($$var);
}
Well, you could already consider writing a function because you do exactly the same thing four times.
Assuming FilterALLHTML is not a custom function.
function Filter($var)
{
if ($var != null)
{
return FilterALLHTML($var);
}
return null;
}
Or just include the null check in the FilterALLHTML function and return null from there, if needed.
So, if you can change FilterALLHTML then you'd do it like this:
function FilterALLHTML($var)
{
if ($var == null)
{
return null;
}
else
{
//do your filtering
return $filteredVar;
}
}
Adding to Thorarin's answer, you can change your filterall function in order to accept an array as input, and passing it by reference it will modify the arrays' content.
$tofilter = array($city,$state,$division,$title);
filterall($tofilter);
I didn't see it mentioned, you could always pass the parameters by reference to skip the repeated assignments:
function FilterALLHTML(&$var)
{
if ($var == null)
{
$var = null;
}
else
{
$var = strip_tags($var);
}
}
I believe you can also store references in the array but i haven't tried it.
foreach (array(&$city, &$state, &$title, &$division) as $var)
{
FilterALLHTML($var);
}
I don't think you can improve the performance, but you can shorten the syntax, but it will end up being the same to the interpreter
<?PHP
$city = ($city == NULL) ? "default value" : FilterALLHTML($city);
$state = ($state == NULL) ? "default value" : FilterALLHTML($state);
$title = ($title == NULL) ? "default value" : FilterALLHTML($title);
$division = ($division == NULL) ? "default value" : FilterALLHTML($division);
?>
"default value" should be replaced with what you would like the value to be if the variable is null