I'm building some simple validation rules in php and my IDE (phped) is complaining about the syntax.
Can anyone tell me what is wrong with the following?
function notBlank($str) {
(strlen($str) == 0) ? return false : return true;
}
phped complains of 'unexpected return'
Any advice appreciated.
Thanks.
write it like this:
function notBlank($str){
return strlen($str) != 0;
}
Write it like this:
function notBlank($str) {
return ( strlen($str) == 0 ? false : true );
}
You cant use return within ternary operators. If you want to keep that syntax you have to do something like this:
function notBlank($str = '') {
$var = (strlen($str) == 0) ? false : true;
return $var;
}
Nevertheless do notice that the default way of doing things is more legible:
function notBlank($str = '') {
if(strlen($str) == 0)
return false;
else
return true;
}
Hope it helps!
GSto's answer seems the best here, though you might also like to check out php's empty function:
http://www.php.net/empty
strlen() returns 0 when the string is empty, and in PHP 0==false. So really, it's unnecessary to wrap strlen() in a function. If you want to insist on a boolean answer then cast it. ie:
(bool) strlen($string);
So instead of your function, which is assumably called in an if block, you'd just have
if(strlen($string)) //etc.
Related
I have the following code in numerous places (thousands of places) around my project:
$foo = isset($mixed) ? $mixed : null;
Where $mixed can be anything: array, array element, object, object property, scalar, etc. For example:
$foo = isset($array['element']) ? $array['element'] : null;
$foo = isset($nestedArray['element']['key']) ? $nestedArray['element']['key'] : null;
$foo = isset($object->prop) ? $object->prop : null;
$foo = isset($object->chain->of->props) ? $object->chain->of->props : null;
Is there a way to write this repeated logic as a (simple) function? For example, I tried:
function myIsset($mixed)
{
return isset($mixed) ? $mixed : null;
}
The above function looks like it would work, but it does not in practice. For example, if $object->prop does not exist, and I call myIsset($object->prop)), then I get fatal error: Undefined property: Object::$prop before the function has even been called.
Any ideas on how I would write such a function? Is it even possible?
I realize some solutions were posted here and here, but those solutions are for arrays only.
PHP 7 has a new "Null coalescing operator" which does exactly this. It is a double ?? such as:
$foo = $mixed ?? null;
See http://php.net/manual/en/migration70.new-features.php
I stumbled across the answer to my own question while reading about php references. My solution is as follows:
function issetValueNull(&$mixed)
{
return (isset($mixed)) ? $mixed : null;
}
Calls to this function now look like:
$foo = issetValueNull($array['element']);
$foo = issetValueNull($nestedArray['element']['key']);
$foo = issetValueNull($object->prop);
$foo = issetValueNull($object->chain->of->props);
Hopefully this helps anyone out there looking for a similar solution.
isset is a language construct, not a regular function. Therefore, it can take what would otherwise cause an error, and just return false.
When you call myIsset($object->prop)), the evaluation occurs and you get the error.
See http://php.net/manual/en/function.isset.php
This is the same problem as using typeof nonExistentVariable in JavaScript. typeof is a language construct and will not cause an error.
However, if you try to create a function, you get an error for trying to use an undefined variable.
function isDef(val) {
return typeof val !== 'undefined';
}
console.log( typeof nonExistent !== 'undefined'); // This is OK, returns false
isDef(nonExistent); // Error nonExistent is not defined
You could actually just write it like:
$foo = $mixed?:null;
If you just want to check if it exist do this
function myIsset($mixed)
{
return isset($mixed); // this is a boolean so it will return true or false
}
function f(&$v)
{
$r = null;
if (isset($v)) {
$r = $v;
}
return $r;
}
I want to convert this if/else statement to ternary format:
function session_active()
{
if ($_SESSION['p_logged_in']) {
return true;
}
else {
return false;
};
}
I tried:
function session_active()
{
($_SESSION['p_logged_in'] ? true : false);
}
but it always returns false.
I am looking at the examples at http://davidwalsh.name/php-ternary-examples and this seems correct as far as I can see from the examples. Why does it always return false?
You may try to simple return the $_SESSION['p_logged_in'] value :-
function session_active()
{
return (bool)$_SESSION['p_logged_in'];
}
php isnt ruby, you have to return that value from the ternary.
to elaborate in more detail...
function session_active()
{
return ($_SESSION['p_logged_in'] ? true : false);
}
Try this:
function session_active() {
return (isset($_SESSION['p_logged_in'])) ? true : false;
}
to correct your logic add return in front of your statment
to simplify it do: return (bool)$_SESSION['p_logged_in'];
There is a difference between $_SESSION['p_logged_in'] === true vs $_SESSION['p_logged_in'] != null, by returning $_SESSION['p_logged_in'] could in affect be more than what it is testing for.
is this the right syntax to check if a value is equivalent to NULL or not in PHP:
if($AppointmentNo==NULL)
?
I have tried it but it seems that it is not working. Any suggestion for another syntax?
Thanks
Use is_null():
if(is_null($AppointmentNo)) {
// do stuff
}
Alternatively, you could also use strict comparison (===):
if($AppointmentNo === NULL) {
An example:
$foo = NULL;
if(is_null($foo)) {
echo 'NULL';
} else {
echo 'NOT NULL';
}
Output:
NULL
There is a function called is_null.
is_null($AppointmentNo)
Use is_null().
if (is_null($AppointmentNo))
Typically you would use is_null().
if (is_null($AppountmentNo))
Quick question to do with php functions, it may sound silly to some of you but I dont want to get in to bad habits. Is there anything wrong with doing the following?
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
return false;
}
Instead of;
function do_something($val)
{
$a = 1;
if ($val==$a)
{
return true;
}
else
{
return false;
}
}
Sorry guys I think my example isn't great. Basically the function could insert data into a database or send an email etc. With these functions I may only need to now whether it was successful or not by returning true or false. I wanted to know whether its suitable that I can use the shorter method instead of the if-else block.
I hope that makes it clearer.
Not really. Both works the same. However, it would be much cleaner to write it like this:
function do_something($val)
{
$a = 1;
return ($val==$a) ? true : false;
}
That's totally cool, because when returning a value, the function is left and it doesn't matter what follows.
But you could shorten this with
function do_something($val)
{
$a = 1;
return $val == $a; // this condition will be evaluated to true/false
}
The shortest way to do it:
function do_something($val)
{
return ($val==1) ;
}
No, that is perfectly fine, and in fact advised in multiple cases. :)
function isChongHao(ary,i,j)
if ary(i-1,j)<>0 or ary(i+1,j) then
isChongHao=true
exit function
end if
isChongHao=false
end function
function isChongHao($ary, $i, $j) {
if($ary[$i-1][$j] != 0 || $ary[$i+1][$j]) {
return true;
}
return false;
}
--I suppose $ary contains a name of a function.--
Ooops, strike that: Joel thanks, I totally missed the fact that it was vbscript!!! O.o
Now maybe it is better...
function isChongHao($ary, $i, $j)
{
return ($ary[$i-1][$j] || $ary[$i+1][$j]);
}
You should probably check to ensure those indexes are set in the array beforehand, though, with an isset() call.
Assuming ary is an array
function isChongHao($ary,$i,$j) {
return (($ary[$i-1][$j] || $ary[$i+1][$j]) ? true : false);
}
Assuming ary is a function
function isChongHao($ary,$i,$j) {
return (($ary($i-1,$j) || $ary($i+1,$j)) ? true : false);
}