doudongfu8006 2014-03-04 01:14
浏览 84
已采纳

php check name包含字符串和checkout更多名称

I made a simple function to check if array strings contain a certain name. However, since the names are getting more and more, I have to duplicate elseif all the time. If someone could help me to improve me function please? I'd like to check $arr names.

if the array looks like $arr = array('PDF', 'PSD', 'PNG', 'GIF', 'Mp3', 'JPG'....);

$i can be counted from mysql

 function checkname($arr, $name1, $name2, $name3......... ){
        if (strpos($arr, $name1) !== false) {
            return $name1;
        }elseif(strpos($arr, $name2) !== false){
            return $name2;

        ..............


        }else{
            return ' ';
        }
    }


checkname($arr[$i], 'PDF', 'PSD', 'PNG'........);
  • 写回答

2条回答 默认 最新

  • douju4594 2014-03-04 01:18
    关注

    May I suggest array_slice() and func_get_args() to solve your argument problem?

    <?php
        function checkname($arr, $name) {
            foreach (array_slice(func_get_args(), 1) as $name) {
                if (strpos($arr, $name) !== false) {
                    return $name;
                }
            }
    
            return '';
        }
    ?>
    

    ..alternately, to solve it into infinity (or however many array values your memory can handle) why not pass an array, and simply do the following:

    <?php
        function checkname($arr, $names) {
            foreach ($names as $name) {
                if (strpos($arr, $name) !== false) {
                    return $name;
                }
            }
    
            return '';
        }
    
        checkname($arr[$i], array('PDF', 'PSD', 'PNG'));
    ?>
    

    Note:

    Your current code checks for the position of PDF, PSD, PNG etc., anywhere in your name (in uppercase!!), so MYPNG.PHP would go through fine, and doge.png would fail.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline