简体   繁体   English

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

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

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) 我需要先添加条件,例如,如果变量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

}

As you said:- 如你所说:-

I mean search the value of variable into that array, If true, then display the 2=>25. 我的意思是将变量的值搜索到该数组中,如果为true,则显示2 => 25。 Example if 25 has a value in array $arr , true. 例如,如果25在数组$ arr中具有值,则为true。 Then display 2=>25 然后显示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 输出: -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 注意:-如果两个值在数组中相同并且您正在搜索该值,那么上面的代码将只给出第一个匹配项,而不是第二个匹配项

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

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