0

有没有更好的方法来编写这种设置变量并在循环后检查它的值的模式?

<?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: ...');
}

似乎有更好的方法来写这个。

4

2 回答 2

2
if (!array_filter($posts, function ($post) use ($id) { return $post->id == $id; })) {
    header(...);
}

(可以选择先将该长衬线分配到一个变量中,以使其更具可读性。)

如果您偏爱功能性 PHP

if (F\none($posts, function ($post) use ($id) { return $post->id == $id; })) {
    header(...);
}

差别不大,但读起来更好。

于 2013-05-29T19:06:02.723 回答
-1

你可以做这样的事情来缩短它,但就是这样......

<?php
foreach ($posts as $post) {
    // If post ID matches the request ID
    if($post->id != $id) {
        header("Location: ...");
        exit;
    }
}
于 2013-05-29T19:01:43.593 回答