簡體   English   中英

如何檢查字符串是否不存在,然后返回false?

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

如果$ str不存在,我試圖使代碼返回false

這是我嘗試過的方法(但是沒有用):

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());

輸出說:

PHP Warning:  Missing argument 1 for rev_epur_str() 

它只是返回一個錯誤而不是false

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

如果$str為空,如何返回false?

您可以在PHP中設置參數的默認值。 下面的代碼使$str為可選參數,同時,它執行empty檢查以返回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

注意:原始代碼中顯示的錯誤是完全有效的,您已設置函數使用參數,因此必須向其傳遞參數,即除非為該參數使用默認值(已完成此操作)以上)。

現場例子

復制

閱讀材料

默認參數

無需返回布爾值回顯字符串,因此可以確定它是否可以正常工作:

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';
    }
}

你必須像這樣調用函數

var_dump(rev_epur_str($ str));

意味着$ str應該有一些值;

您的代碼會引發錯誤,因為您在函數中聲明了一個參數,並且沒有任何參數就調用了它。

解決此問題並允許不帶參數調用函數的一種方法是聲明這樣的默認值(此處為NULL ):

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

此外,僅當變量從未設置或為NULL時,才測試isset 如果您希望它使用空字符串,則可以嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM