什么可以替代逻辑运算符||因此,if语句并不总是评估为true

时间:2018-10-20 07:50:52

标签: php

if现有个人资料图片之前,我有以下要评估的unlink语句,但前提是它不是初始的默认个人资料图片。

    //Checks to see if the unlink file is the default image on sign-up (if it is, don't delete)
    if($user['profile_pic'] != "assets/images/profile_pics/defaults/prof_img_black.png"
        || $user['profile_pic'] != "assets/images/profile_pics/defaults/prof_img_blue.png"
        || $user['profile_pic'] != "assets/images/profile_pics/defaults/prof_img_green.png"
        || $user['profile_pic'] != "assets/images/profile_pics/defaults/prof_img_red.png"
        || $user['profile_pic'] != "assets/images/profile_pics/defaults/prof_img_yellow.png"
        ){
        unlink($user['profile_pic']);
    }
    else{
        null;
    }

我在逻辑运算符||上发现的问题是,即使这些语句之一为true,也全部为true,但只有false都是false。问题是,其中至少有一个将始终为真,因此unlink是文件夹中的默认图像。默认图像(不同颜色)在注册时随机分配。

我可以使用||以外的其他方式进行评估吗?

2 个答案:

答案 0 :(得分:1)

将您的运营商从!=更改为==,然后交换流程

//Checks to see if the unlink file is the default image on sign-up (if it is, don't delete)
if($user['profile_pic'] == "assets/images/profile_pics/defaults/prof_img_black.png"
    || $user['profile_pic'] == "assets/images/profile_pics/defaults/prof_img_blue.png"
    || $user['profile_pic'] == "assets/images/profile_pics/defaults/prof_img_green.png"
    || $user['profile_pic'] == "assets/images/profile_pics/defaults/prof_img_red.png"
    || $user['profile_pic'] == "assets/images/profile_pics/defaults/prof_img_yellow.png"
    ){
     null;
}
else{
    unlink($user['profile_pic']);
}

答案 1 :(得分:0)

另一个有助于消除某些冗余的想法是使用匹配项:

<?php
# Match the path string and color
preg_match('!assets/images/profile_pics/defaults/prof_img_([^.]+)\.png$!', $user['profile_pic'], $match);
# If it doesn't require a match of only 'black','blue','green','red', or 'yellow', this may be fine to stop here with true/false
# if(empty($match[1]))
#     unlink($user['profile_pic']);
# If there are a possibility of more colors, you can match the found color to only your select few colors
$color  =   (!empty($match[1]))? $match[1] : false;
# If there is a possibilty of other colors and only these should be matched, then you can check from a list of colors here
if(!in_array($color, ['black','blue','green','red','yellow'])){
    # If not found, unlink
    unlink($user['profile_pic']);
}