Using ismobile

I have this code:

$ismobile = check_user_agent(‘mobile’);

function check_user_agent ( $type = NULL ) {
$user_agent = strtolower ( $_SERVER[‘HTTP_USER_AGENT’] );
if ( $type == ‘bot’ ) {

            // matches popular bots
            if ( preg_match ( "/googlebot|adsbot|yahooseeker|yahoobot|msnbot|watchmouse|pingdom\.com|feedfetcher-google/", $user_agent ) ) {
                    return true;
                    // watchmouse|pingdom\.com are "uptime services"
            }
    } else if ( $type == 'browser' ) {
            // matches core browser types
			 
            if ( preg_match ( "/mozilla\/|opera\//", $user_agent ) ) {
                    return true;
            }
    } else if ( $type == 'mobile' ) {
            // matches popular mobile devices that have small screens and/or touch inputs
            // mobile devices have regional trends; some of these will have varying popularity in Europe, Asia, and America
            // detailed demographics are unknown, and South America, the Pacific Islands, and Africa trends might not be represented, here
			 
            if ( preg_match ( "/phone|iphone|itouch|ipod|symbian|android|htc_|htc-|palmos|blackberry|opera mini|iemobile|windows ce|nokia|fennec|hiptop|kindle|mot |mot-|webos\/|samsung|sonyericsson|^sie-|nintendo/", $user_agent ) ) {
                    // these are the most common
                    return true;
            } else if ( preg_match ( "/mobile|pda;|avantgo|eudoraweb|minimo|netfront|brew|teleca|lg;|lge |wap;| wap /", $user_agent ) ) {
                    // these are less common, and might not be worth checking
                    return true;
            }
    }
    return false;

}

I think it works. But I want to set the width of a table based on whether the device is desktop or mobile.

<?php if ($ismobile) myTableWidth="100%"; else myTableWidth="60%" ; ?>

But this raises the error ‘unexpected =’

What to do?

All help is greatly appreciated.

In PHP, you have to start variable names with a $. This should work:

<?php if ($ismobile) $myTableWidth="100%"; else $myTableWidth="60%" ; ?>

You could also use a ternary operator to do this:

<?php $myTableWidth = $ismobile ? "100%" : "60%"; ?>

You should also note that your server code isn’t the place to do this any more; CSS has built in functionality that allows you to provide different styling based on the user agent. Take a look at CSS media queries for more info.

Sponsor our Newsletter | Privacy Policy | Terms of Service