繁体   English   中英

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

[英]PHP : Get or search values in_array from my variable and display it

我有一个数组,我正在检查变量是否在该数组中有一个值。 同样,也获得相同的值。 我需要先添加条件,例如,如果变量25在我的数组$ arr中具有相同的值,则返回true并显示数组值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

}

如你所说:-

我的意思是将变量的值搜索到该数组中,如果为true,则显示2 => 25。 例如,如果25在数组$ arr中具有值,则为true。 然后显示2 => 25

您可以像下面这样:

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

输出: -https : //eval.in/646272

注意:-如果两个值在数组中相同并且您正在搜索该值,那么上面的代码将只给出第一个匹配项,而不是第二个匹配项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM