Check which day is not avaliable in PHP array

我的未来我决定 提交于 2021-02-17 07:11:06

问题


I have an array which consists of 7 days names. This array will be dynamic everytime. So i want to check which day is missing from an array. For ex,

[Monday,Tuesday,Thursday,Friday,Saturday,Sunday]

Here, the wednesday is missing so output should be wednesday

Sometimes there will be more then one day will be missing and sometimes none, so the output should be and array which will contain all missing days.


回答1:


you can compare two arrays with array_diff. Example: https://3v4l.org/4g00a




回答2:


You can use array_diff function to get missing days.

$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$inputDays = ['Sunday','Friday'];
$missingDays = array_diff($days,$inputDays);
print_r($missingDays);

Output

Array
(
    [0] => Monday
    [1] => Tuesday
    [2] => Wednesday
    [3] => Thursday
    [5] => Saturday
)

array_diff is case sensitive, you may need to convert string to lower case.

Demo




回答3:


Since you tagged both js and php but didn't specify which language you're using for this part of your code, here's a JS solution (which doesn't have a handy array_diff function)

var days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var input = ["Sunday","Friday"];
return days.filter(function(day) {return input.indexOf(day) < 0;});


来源:https://stackoverflow.com/questions/51347766/check-which-day-is-not-avaliable-in-php-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!