0

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 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

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?
There should be a 'delete' link below your question.
There were to many answers and votes for the system to allow me to delete it…
2

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.

5 Comments

After running a test in PHP, in_array("23", array("234")) does return false, not true.
If you set the third parameter (strict) to true, it will strictly check types, ie « (in_array("23", array(23), true)) == false »
I didn't notice the // true after the third example.. it's a typo yeah?
@intuited: It was, I fixed it a few moments after posting it though.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.