21
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
  • 2,076
  • 2
  • 23
  • 26

5 Answers5

35

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
  • 2,075
  • 2
  • 25
  • 36
Matt
  • 7,022
  • 16
  • 53
  • 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
23

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
  • 428,835
  • 81
  • 738
  • 806
4
if (strpos($_POST['id'], "gm") === 0) {
  $_SESSION['game'] ="gmod"
}
if (strpos($_POST['id'],"tf2") === 0) {
  $_SESSION['game'] ="tf2"
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
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
  • 89,455
  • 62
  • 89
  • 125
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
  • 71,436
  • 58
  • 190
  • 262