Link to home
Start Free TrialLog in
Avatar of BR
BRFlag for Türkiye

asked on

how can I check for the firs three letters of the word with php?

how can I check for the firs three letters of the word with php?
if my $customerid variable starts with the text "934" I'd like to say "true" the otherwise I'd like to say "false"
SOLUTION
Avatar of Rgonzo1971
Rgonzo1971

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Follow up (for interest)
substr_compare runs almost in linear time - the length of the string and substring have little impact on running time
the other method increases the longer the strings get.

Consider this sample
<?php
$test = "934373648487548378374238943248726348268234";
$sub = "9343736484875483783742389432487263482682";
$len = strlen($sub);
$start = microtime(true);
for($i = 0; $i < 100000;$i++) {
  if (substr($test, 0, $len) == $sub) {
    $result = true;
  }
  else {
    $result = false;
  }
}
$end = microtime(true);
$one = $end - $start;
$start = microtime(true);
for($i = 0; $i < 100000;$i++) {
  $result = substr_compare($test, $sub, 0, $len);
}
$end = microtime(true);
$two = $end - $start;
echo "One: {$one}<br/>";
echo "Two: {$two}<br/>";

Open in new window

Results for the above
One: 0.15969896316528
Two: 0.019267082214355

Open in new window

With
$sub="934"
One: 0.029422044754028
Two: 0.018805027008057

Open in new window

Avatar of BR

ASKER

thank you all
@Braveheartli,

Is there any particular reason you did not choose the first post as the correct answer - it is the same as the accepted post but was there first - by acknowledgement of the second poster?
Avatar of BR

ASKER

Dear Julian Hansen,
I'm pretty sure that your answer was correct
I tried yours answer first, but somehow i couldn't get the result...most  probably my fault
@Braverhertli,

I was not referring to my answer I was referring to Rgonzo1971.

if (substr($customerid ,0,3) == "934") echo "yes";

Open in new window


This was posted first and is the same as the accepted answer.