Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中验证更好、更简洁的模式?_Php - Fatal编程技术网

在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(...);
}