Emily Turcato
Emily Turcato

Reputation: 591

Using in_array for array

So, I have the following php:

<?php 
$user_id = get_current_user_id();   
$user_number= get_user_meta($user_id, 'number', false); 
$numbers= print_r($user_number);    
?>

I get the following:

Array
(
[0] =&gt; Array
    (
        [1] =&gt; 769099
        [2] =&gt; 768785
        [3] =&gt; 769135
        [4] =&gt; 769118
        [5] =&gt; 769136
        [6] =&gt; 769122
        [7] =&gt; 769130
    )

)

Now, I am trying to use in_array to add a condition as following:

<?php if (in_array ($number_id, $numbers)){?>

where $number_id is one of the number in the array.

I have two questions:

Do I have to use print_r to get the values instead of simply saying Array in order to use in_array?

How do I actually user in_array? in this case?

(For example, using the get_user_meta, I simply get Array. I don't want to use print_r. How do I do this? Thanks!)

Upvotes: 1

Views: 110

Answers (3)

Sugumar Venkatesan
Sugumar Venkatesan

Reputation: 4028

try this

<?php if (in_array ($number_id, $user_number[0])){?>

Upvotes: 0

Hardik Solanki
Hardik Solanki

Reputation: 3195

print_r() is normally print your array. Your code Should be:

<?php 
$user_id = get_current_user_id();   
$user_number= get_user_meta($user_id, 'number', false);   
?>

If you want to check number_id in your current user number array than your code should be :

if(in_array('769118',$user_number[0])){ // 769118 is $number_id
    echo "Match Found";
}else{
    echo "No Match Found";  
}

You can refer this link : in_array

Upvotes: 3

deviloper
deviloper

Reputation: 7240

print_r() is only a function to display the values within an array.

In your case the function get_user_meta() retrieve the numbers associated with the user_id and nothing more.

And the function in_array() is there to check to the existence of a specific value within an array.

Upvotes: 1

Related Questions