2013-05-29 33 views
0

有沒有更好的方法來編寫這種設置變量並在循環後檢查其值的模式?在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! 
    header('Location: ...'); 
} 

看來會有更好的寫作方式。

+1

如果$ posts只是一個ID數組,那麼它會是一個簡單的'if(in_array($ posts,$ id))',但由於它是一個多維構造,所以這是行不通的,再次陷入循環。 –

+0

^你可以投它,但我會堅持循環:) –

回答

-1

你可以做這樣的事情,使之短,但也差不多了......

<?php 
foreach ($posts as $post) { 
    // If post ID matches the request ID 
    if($post->id != $id) { 
     header("Location: ..."); 
     exit; 
    } 
} 
+0

這不一樣。 – deceze

+0

這會在第一個不匹配的id上中止,這不是OP想要的。 OP的看看是否至少有一個匹配的IP,在這種情況下不要重定向。 –

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

(可選,長期內襯分配到一個變量先使其更具可讀性。 )

如果你偏愛Functional PHP

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

差別不是很大,但讀得更好。