-1

I'm a newb and I got a problem with in_array...

So this is my array $allUsers (received by a SQL-Query for Usernames)

    Array
(
    [0] => Array
        (
            [name] => test
        )

    [1] => Array
        (
            [name] => test2
        )

    [2] => Array
        (
            [name] => admin
        )

    [3] => Array
        (
            [name] => kingChräbi
        )

Now If a new member wants to register, I want to check in this array if it's already existent:

if(!in_array($username,$allUsers)){....

eventhough it is to when $username is NOT in $allUsers do .... it's just skipping to else also if the user is existing :(

$username is set before with

$username = $_POST['name'];

and working as it should (i can echo it without a problem, is exactly test or test2 without whitespace or anything)

I really looked around alot, but I can't find anything like my problem here... Could you please help me?

Thanks

Michael
  • 279
  • 2
  • 5
  • 14
  • `in_array()` requires a **value** and **a single-dimensional array**. You're currently passing a 2 d array. That's why it doesn't work. – Amal Murali Mar 24 '14 at 16:29
  • alright, So I should write a function returning true / false with a foreach in it. – Michael Mar 24 '14 at 16:32

4 Answers4

2

although question itself is quite silly, as you have to realize what array you are working with, the quick solution, based on PDO tag, would be as follows: instead of fetchAll() use fetchAll(PDO::FETCH_COLUMN)

Or, rather you need to learn SQL as well, and find users not by means of selecting them ALL from database which makes no sense, but by asking a database to find a user for you

$stm = $pdo->prepare("SELECT * FROM table WHERE name=?");
$stm->execute(array($_POST['name']));
$user = $stm->fetch();

if ($user) { // <---HERE YOU GO
Your Common Sense
  • 152,517
  • 33
  • 193
  • 313
0

The in_array() does not work with multi-dimensional arrays. You better flatten your array and then do a search for the keyword.

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); //<-- Pass your array here
$new_arr = array();
foreach($it as $v) {
    $new_arr[]=$v;
}
if(in_array('test',$new_arr))
{
    echo "Exists !";
}

Working Demo

Shankar Damodaran
  • 65,155
  • 42
  • 87
  • 120
0

You are searching a 2-D array for a value under the key of "name".
Using array_map() or simple foreach loop should work -

$username = "admin";
$key = "name";
if(!in_array($username,array_map(function($v)use($key){return $v[$key];},$allUsers))){
    echo "No found";
}else{
    echo "Found";
}
Kamehameha
  • 5,258
  • 1
  • 19
  • 26
-1

If you are using:

While ($ row=mysql_fetch_assoc ($ result) {

$ data [] = $ row }

Remove the [] to not create a multidimensional array.

Ryguydg
  • 93
  • 1
  • 8