PHPHelpPls PHPHelpPls - 4 months ago 7
PHP Question

PHP Array, Then check if in data

I'm checking every possible thing in the array to see if it contains something from the data specified.

Array:

$dogs = [
"terrier" => "Terrier",
"german_shepard" => "GS",
];


Code:

if ($stmt->execute()){
while ($request = $stmt->fetch(PDO::FETCH_ASSOC)){
foreach($dogs as $x => $x_value){
if (strpos($request['Data'], $x) !== false) { // This bit!!
$dog = $x_value;
} else {
$dog = 'Unknown dog';
}
}
}
}


I then have a list, It can detect the first one in the list fine, but others it just calls 'Unknown dog' EG:


1 - Terrier

2 - Unknown Dog

3 - Unknown Dog


I want it to appear like:


1 - Terrier

2 - GS

3 - GS


I want the list to appear for each value found.

Answer

You are overwriting the $dog variable for each item it checks in $dogs, so if there is anything that doesn't match after the one that does match, it will set it back to 'Unknown dog'. You should set $dog to a default value before your loop, and only overwrite it if it is found.

$dog = 'Unknown dog';
foreach($dogs as $x => $x_value){
    if (strpos($request['Data'], $x) !== false) { // This bit!!
        $dog = $x_value;
    }
}

There may be more than one value in $dogs that matches a particular instance of $request['Data']. If you use this code, $dog will be set to the last value from from $dogs that matches $request['Data']. If you want it to be set to the first matching value, then add a break; after $dog = $x_value; If you want something other than first or last, it will need to be more complex than this.

Comments