Vadiklk
Vadiklk

Reputation: 3764

What is the simplest of checking first and last character of a string in php

What is the simplest way of checking whether the first letter of a string $str is 'a' and the last letter is 'a' too?

Upvotes: 13

Views: 12294

Answers (3)

TNC
TNC

Reputation: 5386

if(substr($str, 0,1) == "a" && substr( $str,-1) == "a")
{
    // code
}

Upvotes: 8

qbert220
qbert220

Reputation: 11556

Or use substr to get the last character:

if($str[0] == 'a' && substr($str,-1) == 'a') {
    //do whatever you wanted
}

Upvotes: 2

The GiG
The GiG

Reputation: 2611

if($str[0] == 'a' && $str[strlen($str) - 1] == 'a') {
    //do whatever you wanted
}

Upvotes: 24

Related Questions