views:

68

answers:

2

ANSWERED: THE FUNCTION WORKS AS I WANTED IT TO. I HAD A TYPO IN MY TEST PHP THAT MADE IT RETURN TRUE REGARDLESS.

I am using in_array, and I'm trying to use it in a way where it will only return true if it's an exact match of one of the objects in the array, not just if it's "in" the array. e.g.

1. $sample_array = array('123', '234', '345');
2. $sample_array = array('23', '34', '45');

in_array('23', $sample_array);

In the above example, I would only want version 2 to return true, because it has the exact string, '23'. Version 1 returns true as well though, because the array contains instances of the string '23'.

How would I get this to work so that only version 2 returns true? Am I even using the right function?

+2  A: 

This function is not a regex function. It checks to see if that exact value is in the array, not something that is 'like' that value. Checking if '23' is in an array will not return true for '234'.

in_array("23", array("23")); // true
in_array("23", array(23)); // true
in_array("23", array("234")); // false (0)

Notice, however, that it will check against different castings.

animuson
After running a test in PHP, `in_array("23", array("234"))` *does* return false, not true.
animuson
If you set the third parameter (strict) to true, it will strictly check types, ie « (in_array("23", array(23), true)) == false »
intuited
@animuson I didn't notice the // true after the third example.. it's a typo yeah?
intuited
@intuited: It was, I fixed it a few moments after posting it though.
animuson
My bad— I had accidentally put a semicolon directly after my "if" statement, so everything was echoing true regardless. It's working just like it should.
Kerri
+1  A: 

Version 1 does not return true. The function works exactly as it should.

<?php

$sample_array1 = array('123', '234', '345');
$sample_array2 = array('23', '34', '45');

echo in_array('23', $sample_array1);        // 0
echo in_array('23', $sample_array2);        // 1
Coronatus
You're completely right. I had an extra semicolon in my php that was echoing my test as "YES" regardless of the "if" statement.Do you know if there is a way I can remove this question so as not to confuse anyone?
Kerri
There should be a 'delete' link below your question.
animuson
There were to many answers and votes for the system to allow me to delete it…
Kerri