Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array() not working

Tags:

html

php

My code:

<?php

$pass = "12345";

//checkPass($pass, $user, $length);
$file = file_get_contents("common.txt");
$array = explode("\n", $file);
if(in_array($pass, $array) == true) {
 echo "it's in the array";
}
?>

first few lines of the array (i used print_r($array)...):

Array ( [0] => 12345 [1] => abc123 [2] => password [3] => computer [4] => 123456 
[5] => tigger [6] => 1234 [7] => a1b2c3 [8] => qwerty [9] => 123 [10] => xxx 
[11] => money [12] => test [13] => carmen [14] => mickey [15] => secret 
[16] => summer [17] => internet [18] => service [19] => canada [20] => hello 
[21] => ranger [22] => shadow [23] => baseball [24] => donald [25] => harley 
[26] => hockey [27] => letmein [28] => maggie [29] => mike [30] => mustang 
[31] => snoopy
like image 898
Andrew Avatar asked Nov 14 '09 01:11

Andrew


People also ask

What is the use of in_array () function?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

Does in_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How do you check key is exist in array or not in PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How do I view an array in PHP?

To display array structure and values in PHP, we can use two functions. We can use var_dump() or print_r() to display the values of an array in human-readable format or to see the output value of the program array.


1 Answers

If your file uses Windows linebreaks (lines end in \r\n), you'll get an invisible \r character at the end of each of your strings. Test for it by running strlen() on one of them:

echo $array[0] . ': ' . strlen($array[0]) . ' chars';

If you get something like

12345: 6 chars

You know that's the problem! You can get rid of these characters after exploding the array using array_map() with trim():

$array = array_map('trim', $array);
like image 198
Paige Ruten Avatar answered Oct 14 '22 13:10

Paige Ruten