2014-10-02 53 views
0

只需要一点帮助,在这里进行个人学习项目。我搜索了许多类似的帖子,但没有运气。在其他地方使用数组 - 如果声明

我们的目标是通过使用中的数组,以缩短我的代码如下否则-if语句(而不是其他40多个-IF的重新迭代同样的事情)。如果我拼出每个其他-if语句,我只是希望提高它

下面的代码工作。

<?php 
$affiliate1 = array('productA', 'productB', 'productC', 'productD', 'ProductE', 'productF'); 
?> 

<?php 
$affiliate2 = array('productG', 'productH', 'productI', 'productJ', 'ProductK', 'productL'); 
?> 

<?php $returnaddress = $_POST['product_name']; ?> 
<?php if ($returnaddress == "$affiliate1") $returnaddress = 'Address1'; 
elseif ($returnaddress == "$affiliate2") $returnaddress = 'Address2'; 
?> 

<?php echo $returnaddress;?> 

任何帮助/解释是非常感谢!我搜索了几个小时,但没能找到足够我的案例的例子。

+1

工作代码您是否在寻找['in_array()'](http://php.net/manual/en/function.in-array.php) - > 'if(in_array($ returnaddress,$ affiliate1))$ returnaddress ='Address1'; elseif(in_array($ returnaddress,$ affiliate2))$ returnaddress ='Address2';'? – Sean 2014-10-02 20:27:17

+0

为什么在你的代码之间的“$ affiliate1? – 2014-10-02 20:28:35

+1

为什么不使用[转](http://php.net/manual/en/control-structures.switch.php)? – wavemode 2014-10-02 20:29:15

回答

0

感谢肖恩指出这一点!我需要使用in_array,我不知道它存在!

这里是他提供

<?php 
$affiliate1 = array('productA', 'productB', 'productC', 'productD', 'ProductE', 'productF'); 
?> 

<?php 
$affiliate2 = array('productG', 'productH', 'productI', 'productJ', 'ProductK', 'productL'); 
?> 


if (in_array($returnaddress, $affiliate1)) $returnaddress = 'Address1'; 
elseif (in_array($returnaddress, $affiliate2)) $returnaddress = 'Address2'; 
+0

只是一个提示 - !如果你“再编写一个脚本,仅仅是PHP的,你不需要打开和关闭''每报关单行,刚开始用' 2014-10-02 21:35:45

+0

谢谢!知道了,你可能会对完整的代码感到畏惧,我会开始寻找到那 – James 2014-10-02 21:45:01

+0

无论如何,它应该为你节省一点打字费用! :d – 2014-10-02 21:49:07