20
if ($_POST['id'] beginsWith "gm") {
$_SESSION['game']=="gmod"
}
if ($_POST['id'] beginsWith "tf2") {
$_SESSION['game']=="tf2"
}

How to do this so it will work?

Riki137
  • 1,367
  • 2
  • 16
  • 23

5 Answers5

34

You could use substring

if(substr($POST['id'],0,3) == 'tf2')
 {
  //Do something
 }

Edit: fixed incorrect function name (substring() used, should be substr())

Zak Henry
  • 1,971
  • 2
  • 24
  • 35
Matt
  • 6,702
  • 16
  • 52
  • 66
  • 3
    +1. this should be (marginally) faster than strpos since it won't traverse the entire string on failure. – Emil Vikström Apr 29 '11 at 16:54
  • @EmilVikström I **seriously** doubt your statement about `substr()` being faster than `strpos()`. In fact I believe it will be *slower*! – PeeHaa Aug 09 '12 at 08:44
24

You can write a begins_with using strpos:

function begins_with($haystack, $needle) {
    return strpos($haystack, $needle) === 0;
}


if (begins_with($_POST['id'], "gm")) {
    $_SESSION['game']=="gmod"
}

// etc
Jon
  • 413,451
  • 75
  • 717
  • 787
4
if (strpos($_POST['id'], "gm") === 0) {
  $_SESSION['game'] ="gmod"
}
if (strpos($_POST['id'],"tf2") === 0) {
  $_SESSION['game'] ="tf2"
}
gen_Eric
  • 214,658
  • 40
  • 293
  • 332
3

NOT the fastest way to do it but you can use regex

if (preg_match("/^gm/", $_POST['id'])) {
    $_SESSION['game']=="gmod"
}
if (preg_match("/^tf2/, $_POST['id'])) {
    $_SESSION['game']=="tf2"
}
Toto
  • 86,179
  • 61
  • 85
  • 118
2
function startswith($haystack, $needle){ 
    return strpos($haystack, $needle) === 0;
}

if (startswith($_POST['id'], 'gm')) {
    $_SESSION['game'] = 'gmod';
}
if (startswith($_POST['id'], 'tf2')) {
    $_SESSION['game'] = 'tf2';
}

Note that when assigning values to variable use a single =

PeeHaa
  • 69,318
  • 57
  • 185
  • 258