0

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!

3
  • what happens if you try in_array( $uid, $friend_array[0] ) Commented Aug 6, 2011 at 23:21
  • Worth to mention: $is_friend = in_array($uid, $friend_array) is much more readable and does exactly the same. Commented Aug 6, 2011 at 23:29
  • The values are coming from SQL. I have a field called "friend_array" and it contains a comma separated list of values. Do I need to do a foreach within my while loop? I am terrible with arrays. Commented Aug 6, 2011 at 23:33

3 Answers 3

5

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';
Sign up to request clarification or add additional context in comments.

1 Comment

This is really helpful...I think I need to read more about arrays and see if there's a more efficient way to do this. Thanks for your response!
3

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.