There are a couple of issues with your code. First $browsers.length
is not the way that value is calculated in PHP. It seems like .length
is a JavaScript format? It should be count($browsers)
. Also, you have SERVER['HTTP_USER_AGENT']
when it should be $_SERVER['HTTP_USER_AGENT']
. I also changed your echo
format so it’s more readable. This should work without failing completely:
browser();
function browser() {
$browsers = array('chrome', 'msie', 'firefox', 'safari');
for ($i = 0; $i < count($browsers) + 1; $i++) {
if ($_SERVER['HTTP_USER_AGENT'] == $browsers[$i]) {
echo "You are using " . $browsers[$i] . ".";
}
}
}
But if I were you I would approach your logic as so using in_array
instead of a for
loop:
browser();
function browser() {
$browsers = array('chrome', 'msie', 'firefox', 'safari');
if (in_array($_SERVER['HTTP_USER_AGENT'], $browsers) {
echo "You are using " . $_SERVER['HTTP_USER_AGENT'] . ".";
}
}
Basically that for
loop is excessive for the logic presented. Just use in_array
to check of the value of $_SERVER['HTTP_USER_AGENT']
is actually in $browsers
.
That said, browser detection is not as simple as your overall logic implies. But this at least solves your most immediate PHP problems at gives you something to build on.