bDir
bDir

Reputation: 173

Get first letter of a word using PHP

Is it possible to set variable verification if just front of variable contains S ?

Example in my code :

$a = "S0225";
$b = "700S4";

if(strpos($a, 'S') !== FALSE) {
    echo "PASS";
    //for this It will pass
}

if(strpos($b, 'S') !== FALSE) {
    echo "PASS";
    //for this, why this pass too, whereas I want just value of variable start front S
}

Upvotes: 0

Views: 107

Answers (4)

majidarif
majidarif

Reputation: 20105

strpos returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

So to make sure that S is at the beginning of the string, it means S should be found at position 0.

// Note our use of ===.  Simply == would not work as expected
// because the position of 'S' is the 0th (first) character.
// this will make sure that it is also comparing it with an Integer.
if(strpos($a, 'S') === 0)
{
  echo "PASS";
}

A warning from the docs:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Upvotes: 3

Mr. Alien
Mr. Alien

Reputation: 157414

You can also use substr() for this purpose

if(substr($string_goes_here, 0, 1) === 'S') {
    //Pass
}

Upvotes: 3

GautamD31
GautamD31

Reputation: 28763

Try with

if(strpos($b, 'S') == 0) {
    echo "PASS";
}

You can also try with substr like

if (substr($b, 0, 1) == 'S') {
    echo "PASS";
}

Upvotes: 1

Check like this instead..

if(strpos($b, 'S')==0)  //<---- Check for position instead of boolean
{
    echo $b; // Will not print..
}

Upvotes: 1

Related Questions