Reputation: 37
I would like to convert empty strings to zero as an INT. Is it possible not to use "if" statements?
$string = "";
echo $string; // The result must be 0 as INT.
Upvotes: 1
Views: 7476
Reputation: 6560
The only real way is to typecast:
<?php
$str = '';
echo (int)$str;
However, if this is dynamically assigned then you'll have to use an if statement. But fear not, ternary exists:
echo (empty($str) ? 0 : $str);
With the thanks of Dharman, we can Elvis it up a bit:
echo $str ?: 0;
Though, note that if $str
is not defined PHP will throw a undefined notice. For that reason either stick to ternary or ensure the variable is declared before usage.
Upvotes: 7
Reputation: 46
$string = "";
echo intval($string); // the int value of the string
For more info, may read: https://www.php.net/manual/en/function.intval.php
Upvotes: 1
Reputation: 6388
typecasting will do that
echo (int) $string;
Working example : https://3v4l.org/CM2q7
Upvotes: 1
Reputation: 421
Hope this helps. Just typecase the string to int.
$string="";
echo (int)$string;
Upvotes: 0