开发者

checking to see if a vaule is in a particular key of an array

开发者 https://www.devze.com 2023-02-01 01:38 出处:网络
I\'m new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:

I'm new to working with arrays so I need some help. With getting just one vaule from an array. I have an original array that looks like this:

 $array1= Array(   
     [0] => 1_31   
     [1] => 1_65  
     [2] => 29_885...)

What I'm trying to do is seach for and return just the value after the underscore. I've figured out how to get that data into a second array and return the vaules as a new array.

    foreach($array1 as $key => $value){
    $id = explode('_',$value);
}

which gives me:

Array ( [0] => 1  [1] => 31 ) 
Array ( [0] =&开发者_高级运维gt; 1  [1] => 65 ) 
Array ( [0] => 29 [1] => 885 )

I can also get a list of the id's or part after the underscore by using $id[1] I'm just not sure if this is the best way and if it is how to do a search. I've tried using in_array() but that searches the whole array and I couldn't make it just search one key of the array.

Any help would be great.


If the part after underscore is unique, make it a key for new array:

$newArray = array();
foreach($array1 as $key => $value){
    list($v,$k) = explode('_',$value);
    $newArray[$k] = $v;
}

So you can check for key existence with isset($newArray[$mykey]), which will be more efficient.


You can use preg_grep() to grep an array:

$array1= array("1_31", "1_65", "29_885");
$num = 65;
print_r(preg_grep("/^\d+_$num$/", $array1));

Outputs:

Array
(
    [1] => 1_65
)

See http://ideone.com/3Fgr8


I would say you're doing it just about as well as anyone else would.

EDIT

Alternate method:

$array1 = array_map(create_function('$a','$_ = explode("_",$a); return $_[1];'),$array1);
echo in_array(3,$array1) ? "yes" : "no"; // 3 being the example


I would have to agree. If you wish to see is a value exists in an array however just use the 'array_key_exists' function, if it returns true use the value for whatever.

0

精彩评论

暂无评论...
验证码 换一张
取 消