DannyCruzeira
DannyCruzeira

Reputation: 574

Issues with in_array

I have the following fairly simple code, where I need to determine if a certain value exists in an array:

$testvalue = $_GET['testvalue']; // 4
$list = '3, 4, 5';
$array = array($list);

if (in_array($testvalue, $array)) { // Code if found } else { // Code if not found }

Even though it is obvious that the number 4 is in the array, the code returns the code inside the else bracets. What have I done wrong?

Upvotes: 0

Views: 168

Answers (3)

jeroen
jeroen

Reputation: 91792

Your array contains just one value, the string 3, 4, 5.

See the example on CodePad.

If you want to convert your string in an array, you can use:

$array = explode(', ', $list);

I have added a space behind the comma, but a safer method would be to use just a comma and then trim all values.

Upvotes: 2

Niloct
Niloct

Reputation: 10015

Change the third line:

$array = array_map('trim', explode(',',$list));

Upvotes: 3

Evert
Evert

Reputation: 99816

$array here is:

$array = array('3, 4, 5');

which is not the same as:

$array = array(3, 4, 5);

So, fix the way you are creating this array.. don't do it from a string.

Upvotes: 3

Related Questions