Reputation: 7425
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.
Upvotes: 0
Views: 229
Reputation: 5824
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 :)
Upvotes: 1
Reputation: 46692
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;
}
Upvotes: 1
Reputation: 523424
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;
}
Upvotes: 1