在PHP中验证更好、更简洁的模式?
有没有更好的方法来编写这种设置变量并在循环后检查其值的模式在PHP中验证更好、更简洁的模式?,php,Php,有没有更好的方法来编写这种设置变量并在循环后检查其值的模式 <?php $isValid = false; foreach ($posts as $post) { // If post ID matches the request ID if($post->id == $id) { $isValid = true; break; } } if(!$isValid) { // Not valid! hea
<?php
$isValid = false;
foreach ($posts as $post) {
// If post ID matches the request ID
if($post->id == $id) {
$isValid = true;
break;
}
}
if(!$isValid) {
// Not valid!
header('Location: ...');
}
您可以做类似的事情来缩短它,但仅此而已
<?php
foreach ($posts as $post) {
// If post ID matches the request ID
if($post->id != $id) {
header("Location: ...");
exit;
}
}
(可选地,首先将该长线性赋值到变量中,以使其更具可读性。)
如果你偏爱:
差别不大,但读起来更好。如果$posts只是一个id数组,那么它将是一个简单的if(in_array($posts,$id))
,但由于它是多维构造,因此不起作用,而且你会陷入循环。^你可以强制转换它,但我只会坚持循环:)这将在第一个不匹配的id上中止,这不是OP想要的。OP正在查看是否至少有一个匹配的ip,在这种情况下,不要重定向。
if (!array_filter($posts, function ($post) use ($id) { return $post->id == $id; })) {
header(...);
}
if (F\none($posts, function ($post) use ($id) { return $post->id == $id; })) {
header(...);
}