I'm doing an if statement to check if a certain value is in an array
if ((!in_array($add['job_type'][$key], $jobtypes))) {
$add['job_type'][$key] = NULL;
}
I did multiple if statements to do the same thing, but i want to do something like this, to put my code smaller and easy to read:
$value = ($value == '0') ? $value = NULL : $value;
How can i do that?
不确定您到底在追求什么,但是无法正常工作...
$add['job_type'][$key] = (in_array($add['job_type'][$key], $jobtypes)) ? $add['job_type'][$key] : NULL;
I don't think the length of the if
statement is your problem if your code is unreadable. I would suspect it's actually because:
I did multiple if statements to do the same thing
Instead of manually specifying multiple if
statements, you can make this a function:
function updateJobType($key) {
if ((!in_array($add['job_type'][$key], $jobtypes))) {
$add['job_type'][$key] = NULL;
}
}
Then invoke it with whichever arguments you like:
updateJobType('job1');
updateJobType('job2');
updateJobType('job3');
That said, it's a bit hard to tell without the full context of the problem, or your full code.
The shortest way to do the first block is:
$add['job_type'][$key] = (in_array($add['job_type'][$key], $jobtypes)) ? : NULL;
But if you have a lot of code doing the same thing with a lot of other arrays, you need to write a function (or method). Now you will have:
function unsetVar(&$value, &$arr){
$value = (in_array($value, $arr)) ? : NULL;
}
Then, call the function this way:
unsetVar($add['job_type'][$key], $jobtypes);
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.