tags:

views:

39

answers:

1

I am having a bit of difficulty with this. I want to allow a user to check if a username is available through an AJAX request. The AJAX request calls my php and PHP returns true if the username is not available or false if available.

I wanted to merge the username into the array (if found) and then use in_array to locate a match. It isn't working this way however.

    $res = // database returns any username that matches - (not an array)
    $banned = // database returns an assoc array of banned names

    array_push($banned, strtolower($res['user']));

    if(!in_array(strtolower($requested), $banned)){
        echo 'available';
    } else {
        echo 'not available';
    }

Here is a sample array from the banned variable:

Array
(
    [0] => bad1
    [1] => bad2
    [3] => 
)

The 3rd key is null because it wasn't found in the $res variable.

Is there a better way to do this? I also need to convert the values in the array to lowercase as well.

+1  A: 

For readability, I reckon this would look better

if (isset($res['user'])) { // is this key set for this array?

    $banned[] = strtolower($res['user']); // append the strtolower`d version 
}
alex
Heya Alex, thanks for the help. Yeah, it looks better, thanks. I'll remove the array_push and use this instead.
Jim
`array_push()` looks messier, and also adds function overhead. See this question too: http://stackoverflow.com/questions/559844/whats-better-to-use-in-php-array-value-or-array-pusharray-value
alex