1

so I am having a case where the array is used to store usernames. function presented here is supposed to check if username exists, echo the information and if the username is unique it should add it to the array.

<?php
function check_if_name_exists ($name = NULL)
{
    $names = array ("Bob", "Alise", "Karl", "Joe");
    if ($name = NULL)
    {
          echo "you didn't input name";
    }
    else
    {
      if (in_array($name , $names) )
        {
          echo "$name alredy used\n";
        }
      else
        {
          echo "name free\n";
          $names[] = $name ;
        }
    }

}
 ?>

however when I call the function with:

check_if_name_exists();

, or if I add a name that does not exist, always as an output I get:

name free

Any help is welcome. thanks

1 Answers1

3
if ($name = NULL)

You are assigning NULL to $name.

When converted to a boolean, NULL becomes false. Thus, it continues in the else-clause. Because NULL isn't present in the $names, the output becomes "name free".

Use === to make comparisons.

vladdeSV
  • 55
  • 1
  • 9
Enrico Dias
  • 1,417
  • 9
  • 21