dongshi1914 2014-10-02 20:23
浏览 59

在Else-If语句中使用数组

Just need a little help here for a personal-learning project. I've searched numerous similar posts with no luck.

The goal is to shorten my code by using an array within the following else-if statement (rather than having 40+ else-if's re-iterating the same thing).

The following code is working if I spell out each else-if statement, I'm simply looking to improve it.

<?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;?>

Any help/explanation is greatly appreciated! I've searched for a few hours but haven't been able to find examples specific enough to my case.

  • 写回答

1条回答 默认 最新

  • dongxili9934 2014-10-02 20:43
    关注

    Thanks to Sean for pointing this out! I needed to use in_array, which I didn't know existed!

    Here's the working code he provided

    <?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';
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度