doupao5296 2016-09-21 18:52
浏览 63
已采纳

PHP:从我的变量中获取或搜索in_array中的值并显示它

I have array I'm checking if my variable has a value in that array. Also, get the same value as well. I need to add condition first, like for example if the variable 25 has a same value in my array $arr return true and display the array value array(2=>25)

$variable = 25;
$arr = array(1=>26, 2=>25 ,3 => 30 ,4 => 31, 5 => 32);

if(in_array($variable , $arr)){

   //get the array value that have in array and display that array and preserve the key
   //print_r($arr) -> 25

}
  • 写回答

1条回答 默认 最新

  • dongsheng4126335 2016-09-21 19:08
    关注

    As you said:-

    I mean search the value of variable into that array, If true, then display the 2=>25. Example if 25 has a value in array $arr , true. Then display 2=>25

    You can do it like below:-

    <?php
    
    $variable = 25;
    $arr = array(1=>26, 2=>25 ,3 => 30 ,4 => 31, 5 => 32);
    
    
    $key = array_search($variable,$arr); // search the value and return the key
    echo $key .'=>'.$arr[$key]; // echo both key and value based on key
    

    output:-https://eval.in/646272

    Note:- if two values are identical in array and you are searching for that value,then the above code will give only first match not second-one

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 qgcomp混合物线性模型分析的代码出现错误:Model aliasing occurred
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'