How to check if a value is present inside an array?

Posted on

Question :

$idofdb = "25";

$myArray = array();
foreach ( $fthi as $codigo ) {
    $myArray[] = $codigo['ImoCodigo'];

$checkValues = array_values($myArray);
$checkString = implode(',', $checkValues); // 3,4,5,6,7,8,9,10,11,12,13,18,19,14,15,2

I’d like to know how to compare $idofdb with $checkString to see if $idofdb is registered in the database. As you can see, the output of $checkString is a string of numbers separated by commas.


Answer :

You do not need all this, just use the in_array() function directly in array :

in_array("25", $fthi)

Or if you feel you should do something else for some reason:

in_array("25", $checkValues)

See running on ideone .


Instead of you transforming an array into a string with comma-separated numbers you can use the in_array :


$os = array("Mac", "NT", "Irix", "Linux"); 
if (in_array("Irix", $os)) { 
    echo "Tem Irix";
if (in_array("mac", $os)) { 
    echo "Tem mac";


Look at the PhpFiddle showing execution.


As friends have said, this is not necessary. But if you still want to check in string , you can use strpos

$pos = strpos($checkString, $idofdb);

if($pos == false) {
    echo 'Não tem cadastrado';
    echo 'A string foi encontrada na db';


Leave a Reply

Your email address will not be published. Required fields are marked *