knowram Posted December 16, 2006 Share Posted December 16, 2006 Is it possible to do a in_array search for a variable that begins with a specific first 4 letters?this would make things easier by far.thanks for the help Quote Link to comment Share on other sites More sharing options...
marcus Posted December 16, 2006 Share Posted December 16, 2006 Do something like this:[code]<?php$arra = array('aaaa','bbbb','abcd');$var = $_GET['var']; // or whatever you whatif(in_array($var,$arra)){echo "oky doky";}else {echo "no oky doky";}?>[/code] Quote Link to comment Share on other sites More sharing options...
knowram Posted December 16, 2006 Author Share Posted December 16, 2006 I was not able to make that work. Really I think I am just looking for a way to see if a variable starts with specific letters.here is an example of what i am trying to do.given $array1 = array('med:1','med:2','med:3','temp','start');I would like to write a for loop something like this[code]for ($i = "0"; $i <= "4"; $i++){ if ($arra1[$i] starts with "med:"){ //do something} else{ // do something different}}[/code] Quote Link to comment Share on other sites More sharing options...
bljepp69 Posted December 16, 2006 Share Posted December 16, 2006 Try something like this:[code]<?php $array1 = array('med:1','med:2','med:3','temp','start'); foreach ($array1 AS $val) { if (preg_match('/^(med\:)/',$val)) { //do something here } else { //do something else here } }?>[/code] Quote Link to comment Share on other sites More sharing options...
keeB Posted December 16, 2006 Share Posted December 16, 2006 I would do it like this:[code]<?php/** * @author: Nick Stinemates // keeb * @description: Searches array for keys beginning with certain char's */ $array1 = array('med:1','med:2','med:3','temp','start'); foreach ($array1 AS $val) { switch ($val) { case strpos($val, "med:"): //do something break; default: //do something else } }?>[/code] Quote Link to comment Share on other sites More sharing options...
Albright Posted December 16, 2006 Share Posted December 16, 2006 The heck? Why are you using a switch when there's only two possibilities? Also, your code will trigger a false positive if the substring is somewhere in the string besides the first four letters.[code]<?php$array1 = array('med:1','med:2','med:3','temp','start');foreach($array1 as $item){ if(strpos($item,"med:")===0){ //Note we used === instead of ==. false==0, but false!==0. //Also note that using strpos instead of regular expressions is faster for simple searches like this. //Do something } else{ //Do something else } }?>[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.