Jeremy
Jeremy

Reputation: 973

PHP: is_array is returning false when it should not

I have this simple one line code:

$thisUserName = is_array($user) ? $user->name : $user;

Here, $thisUserName is giving by $user, means, the condition is_array is returning false, even if print_r is showing that $user is an array.

Any idea, anybody ?

Thanks.

PS. I tried changing that to echo is_array($user) ? 'yes' : 'no' and it is echoing no.

EDIT:

print_r($user) gives

stdClass Object
(
    [id] => 169
    [name] => Cedric
    [username] => pulpfiction
    [email] => [email protected]
    [password] => c22601b4ed1ac11a80955d6c0eeb1933
    [password_clear] => 
    [usertype] => Registered
    [block] => 0
    [sendEmail] => 0
    [gid] => 18
    [registerDate] => 2013-01-30 11:12:10
    [lastvisitDate] => 2013-02-24 19:45:45
    [activation] => 
    [params] => 

    [aid] => 1
    [guest] => 0
)

Upvotes: 3

Views: 7010

Answers (3)

SDC
SDC

Reputation: 14222

is_array() checks whether the variable is an array.

However, your code immediately after it is $user->name, which implies that you are actually expecting it to be an object. is_array() will not return true for objects.

If you want to test if it's an object, you could use is_object() instead of is_array().

However, it would be even better to check if it's an object of the type you expect, in which case you could use instanceof eg:

$thisUserName = ($user instanceof myUserClass) ? $user->name : $user

(where 'myUserClass' is the class name of your user class, obviously)

Hope that helps.

[EDIT]

In a good system, one should know the class name that is expected for any given object, and use instanceof to verify it.

But if you don't know the class name to expect then is_object() will suffice.

(You can find out the class name of an object using get_class(); that might be worthwhile for your own purposes to learn about the system you're using (Drupal?), but there's little point using get_class and intanceof together in this context to actually test the object; just stick with is_object())

Upvotes: 2

Shijin TR
Shijin TR

Reputation: 7768

If you are using object ,Then try this example

    <?php
    $user->name='my_name';
    echo (is_object($user)) ?$user->name:$user;
    ?>

//Result : my_name

Upvotes: 0

kittycat
kittycat

Reputation: 15044

$user is an object not an array. print_r() will still output it all nice looking, but if you look closely at the output you will see not everything will say array, it will have have the object listed. You should be using is_object()

$thisUserName = is_object($user) ? $user->name : $user;

Upvotes: 14

Related Questions