通过使用数组来测试postdata变量来自动化条件函数

时间:2017-04-21 17:17:45

标签: php arrays if-statement post

我有一些问题需要进行以下自动化:

我从表单中获得了许多变量,例如$ a和$ b 我想根据我获得的变量自动化条件测试。

$test = array('a','b');
for($i=0;$i<sizeof($test);$i++)

对于第一个变量a,工作代码为:

if ( $postdata->a !=${$test[$i]}){echo "different";} else {echo "same";} 

对于第二个变量b,工作代码为:

if ( $postdata->b !=${$test[$i]}){echo "different";} else {echo "same";}

我希望通过这样的数组自动化它:

if ( $postdata->$test[$i] !=${$test[$i]}){echo "different";} else {echo "same";} 

但是$postdata->$test[$i]无法正常工作,即使echo $ test [$ i]也会给出一个&#39; a&#39;和&#39; b&#39;。 我尝试过几次&#34;写作&#34;但我无法解决它。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

而不是使用$test[$i]for loop使代码过于复杂,而不是使用foreach。希望这会很好。

Try this code snippet here contains sample input

<?php
ini_set('display_errors', 1);

$test=array('a','b');
foreach($test as $i => $value)
{
    if ($postdata->{$value} != ${$value})
    {
        echo "different";
    } 
    else
    {
        echo "same";
    }
}