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

Asked

Viewed 742 times

5

$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 find out if $idofdb is registered in the database. As we can observe, the output of $checkString is a string of numbers separated by commas.

3 answers

6


3

Instead of you turning an array into a string with separate numbers with comma you can use the function in_array:

<?php

$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 the execution.

  • I’ve read this guide... php da to do here too? I guess not yet right?

  • Well, did you see any references to PHP there? and when we ask "execute code" nothing happens... then, no, can not use php... (I will delete the previous comment and this because already fulfilled its function)

2

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.