1

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.

3
  • You could var_dump or print_r $request to see what you are getting. Showing us would help us help you... Commented Jul 12, 2016 at 17:05
  • 1
    My first thought is: do you have german_shepard in the database? Commented Jul 12, 2016 at 17:06
  • It's still unclear. What are the values stored in the database? And based on what logic are you willing to print these list? Commented Jul 12, 2016 at 17:11

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Side note: try breaking both loops to prevent unnecessary iterations. +1
Damn it sorry you are correct. I was making the answer with a break and then realized what this does...
@FirstOne I added some explanation of how break could be used here.
-1

You may use PHP's native in_array function:

$dog = 'Unknown dog';
$key = in_array(strtolower($request['Data']), $dogs);
if($key >= 0){
    $dog = $dogs[$key];
}

1 Comment

There is a case-insensitive strpos: stripos.

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.