开发者

php conventions in conditions

开发者 https://www.devze.com 2023-02-15 19:53 出处:网络
I have system, that using keywords for some data There are normal keywords and meta keywords - To:all, Tomember: and Togroup:

I have system, that using keywords for some data

There are normal keywords and meta keywords - To:all, Tomember: and Togroup:

and I have following condition to check meta keywords:

if ((strpos($kwd, 'To:all') === 0) ||
    (strpos($kwd, 'Tomember:') === 0) ||
    (strpos($kwd, 'Togroup:') === 0)开发者_如何学Go)
{
    /* ... */
}

I think this way of identifying meta keywords is incorrect.

One more incorrect way is like this:

if ((strpos($kwd, 'To:all') !== FALSE) ||
    (strpos($kwd, 'Tomember:') !== FALSE) ||
    (strpos($kwd, 'Togroup:') !== FALSE))
{
    /* ... */
}

And in my opinion the correct way is:

if ((substr($kwd,0,6) == 'To:all') ||
    (substr($kwd,0,9) == 'Tomember:') ||
    (substr($kwd,0,8) == 'Togroup:'))
{
    /* ... */
}

Any thoughts?


Of the solutions you propose, the second is wrong because it will return true even if the meta-keywords do not appear in the beginning of $kwd. The other two work correctly.

An even better way would be:

function str_starts_with($haystack, $needle) {
    return substr($haystack, 0, strlen($needle)) == $needle;
}

if (str_starts_with($kwd, 'To:all') ||
    str_starts_with($kwd, 'Tomember:') ||
    str_starts_with($kwd, 'Togroup:'))
{
    // ...
}


strpos($kwd, 'To:all') === 0

will check if the $kwd string begins with To:all -- it'll check if the position of To:all in $kwd is 0.


strpos($kwd, 'To:all') !== FALSE

will check if the $kwd string contains To:all -- no matter at which position.


substr($kwd,0,6) == 'To:all'

whill check if the first 6 characters of $kwd are To:all -- which is equivalent to the first solution.


If you want to test the begins with case, you'll use the first or third solution.
Personnaly, I'd go with the strpos-based : I find it easier to read/understand ; but it's mainly a matter of personnal preferences.

If you want to test the contains case, you'll need to use the second solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消