0

Fairly rubbish with PHP, this is a continuation on from my last question.

I have a list of user agents inside an array, and I want an output to be true if the user agent matches one listed inside the array.

This is what I have for a single user agent:

    <?php
        function mediaType(){
           $browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
           $var = 0;
           if ($browser !== false)  { $var = 1; }
           return $var;
        }
    ?>

I want something like this:

<?php

function mediaType(){

    $userAgents = array("iPhone", "Chrome");    
    $browser = $_SERVER['HTTP_USER_AGENT'];
    $var = 0;

    if (in_array($browser, $userAgents)) {
    $var = 1;
    }   

    return $var;        
}

?>

I guess a while loop would be a good option, but I am clueless.

3 Answers 3

1

Here's your sweet and simple method and no need for a separate $var:

function mediaType()
{
    $userAgents = array("iPhone", "Chrome");    
    $browser = $_SERVER['HTTP_USER_AGENT'];
    $var = 0;

    foreach($userAgents as $agent)
        if(strpos($browser, $agent) !== FALSE)
            return 1;

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You should use a foreach loop.

function mediaType(){
   $userAgents = array("iPhone", "Chrome");    
   $browser = $_SERVER['HTTP_USER_AGENT'];

   foreach ($userAgents as $agent) {
     if (strpos($browser, $agent) !== false)
       return 1;
   }
   return 0;
}

Comments

1
function mediaType()
{
    $userAgents = array("iPhone", "Chrome", ....);
    $browser = $_SERVER['HTTP_USER_AGENT'];

    foreach($userAgents AS $userAgent)
    {
        if(preg_match('#' . preg_quote($userAgent, '#') . '#i', $browser))
        {
             return true;
        }
    }

    return false;
}

Edit: Hm I was too late :/ But in comaprison to the other answers I would use preg_match to find the browser :)

6 Comments

Should not use regex (preg_match) unless absolutely required (due to performance issues).
@faileN: You forgotten to escape user agent name with preg_quote.
Should not use regex unless absolutely required (due to omgwtfthatssupposedtobearegex issues).
Yeah sorry, I added preg_quote. I only use this solution in here, because of the i-modifier to disregard casing. Of course this would also be possible with stripos, but the other answers provide just strpos. Since stripos is only available to PHP 5 or later, the preg_replace-solution should also work fine in PHP 4 :)
Why would you use a regular expression when you don’t need the capabilities of regular expressions? By the way: You’ll get an error if $userAgent contains a #.
|

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.