PHP in_array isn't finding a value that is there

孤者浪人 提交于 2019-12-24 12:04:36

问题


I have an array called $friend_array. When I print_r($friend_array) it looks like this:

Array ( [0] => 3,2,5 ) 

I also have a variable called $uid that is being pulled from the url.

On the page I'm testing, $uid has a value of 3 so it is in the array.

However, the following is saying that it isn't there:

if(in_array($uid, $friend_array)){
  $is_friend = true;
}else{
  $is_friend = false;

This always returns false. I echo the $uid and it is 3. I print the array and 3 is there.

What am I doing wrong? Any help would be greatly appreciated!


回答1:


Array ( [0] => 3,2,5 ) means that the array element 0 is a string 3,2,5, so, before you do an is_array check for the $uid so you have to first break that string into an array using , as a separator and then check for$uid:

// $friend_array contains as its first element a string that
// you want to make into the "real" friend array:
$friend_array = explode(',', $friend_array[0]);

if(in_array($uid, $friend_array)){
  $is_friend = true;
}else{
  $is_friend = false;
}

Working example




回答2:


Output of

Array ( [0] => 3,2,5 ) 

... would be produced if the array was created by something like this:

$friend_array = array();
array_push($friend_array, '3,2,5');
print_r($friend_array);

Based on your question, I don't think this is what you meant to do.

If you want to add three values into the first three indexes of the array, do the following:

$friend_array = array();
array_push($friend_array, '3');
array_push($friend_array, '2');
array_push($friend_array, '5');

or, as a shorthand for array_push():

$friend_array = array();
$friend_array[] = '3';
$friend_array[] = '2';
$friend_array[] = '5';



回答3:


Looks like your $friend_array is setup wrong. Each value of 3, 2, and 5 needs its own key in the array for in_array to work.

Example:

$friend_array[] = 3;
$friend_array[] = 2;
$firned_array[] = 5;

Your above if statement will then work correctly.



来源:https://stackoverflow.com/questions/6969638/php-in-array-isnt-finding-a-value-that-is-there

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!