简体   繁体   中英

How do I check if a string doesn't exist and then return false?

I'm trying to make my code return false if the $str doesn't exist

Here is what I tried (but didn't work):

function rev_epur_str($str)
{
    $str = implode(' ', array_map('strrev', explode(' ', $str)));
    $str = preg_replace('/\s+/', '', $str);
    if (isset($str)) 
    {
        return $str;
    }
    else
    {
        return false;
    }
}
var_dump(rev_epur_str());

Output says:

PHP Warning:  Missing argument 1 for rev_epur_str() 

It just returns an error instead of false

var_dump(rev_epur_str("")); // returns string(0) "" instead of FALSE

How do I return false if $str is empty?

You can in PHP set the default value of a parameter. The code below makes $str an optional parameter and at the same time, it does an empty check to return false.

function rev_epur_str($str = '')
{
    if (empty($str))
      return false;

    $str = implode(' ', array_map('strrev', explode(' ', $str)));
    $str = preg_replace('/\s+/', '', $str);

    return $str;
}

var_dump(rev_epur_str()); // false

var_dump(rev_epur_str('str')); // rts

Note: The error shown in your original code is completely valid, you have set that your function takes a parameter therefore you must pass a parameter to it, that is, unless you use a default value for said parameter (which is what has been done above).

Live Example

Repl

Reading Material

Default Arguments

Instead of returning a boolean, echo string, so you can be sure if its working fine:

function rev_epur_str($str)
{
    $str = implode(' ', array_map('strrev', explode(' ', $str)));
    $str = preg_replace('/\s+/', '', $str);
    if (isset($str)) 
    {
        echo $str;
    }
    else
    {
        echo 'false';
    }
}

You have to call the function like

var_dump(rev_epur_str($str));

Means $str should have some value;

Your code throws an error because you declare an argument to your function and you call it without any.

One way to work around this and allow a call to your function without argument is to declare a default value like this (here with the value NULL ):

function rev_epur_str($str = NULL)
{
    //code here
}
rev_epur_str(); //will work

Also, testing isset will only work if the variable never was set or is NULL. If you want it to work with empty string you can try with:

if (empty($str))
{
     return false;
}
//etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM