2

For Example I have this string

$string = "HelloWorld";

And I want to check if the first four letters is equal to "Hell"

if($string[0]=="H"&&$string[1]=="e"&&$string[2]=="l"&&$string[3]=="l");

Is there a better or simplified way of checking this? maybe $string[0-4] or something like that

2
  • Will it always be the first four letters or will there be a time where you would want to check if the word "hell" exists in the string? Commented Jun 28, 2018 at 1:38
  • 2
    just use substring from start index from 0 and length is 4. then make an if comparison, or are you restricted from using functions? Commented Jun 28, 2018 at 1:41

1 Answer 1

1

If you just want to get the first N characters of your string you can use substr

 i.e:
 $string = "HelloWorld";
 $rest   = substr($string , 0, 4);  // returns "Hell"

Or if you want to check if a word exists in the string you can also just use strpos

i.e
$string = "HelloWorld";
$pos = strpos($string , 'Hell'); //will return false if word is not found in string
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.