1

I am sorting out data from my database using PHP and needed to know if the string(varchar) value starts with a letter or a number, so i am writing a function to check this.

Below is my code, I got the first letter of the string and now my next step is to identify if its a Letter or a number,can PHP achieve this? any suggestions would be great thanks!

function StartWith($str) {

     return  $str[0];

}

echo StartWith('AdamSavior');
KaoriYui
  • 912
  • 1
  • 13
  • 43

4 Answers4

4

The proper way using ctype_alpha and ctype_digit functions:

function startWith($str) {
    $c = $str[0];
    if (ctype_alpha($c)){
        return 'alpha';
    } else if (ctype_digit($c)){
        return 'numeric';
    } else {
        return 'other';
    }
}

echo startWith('AdamSavior') . PHP_EOL;
echo startWith('33man') . PHP_EOL;
echo startWith('---way') . PHP_EOL;

The output (consequtively):

alpha
numeric
other
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
2

To be more simple:

function StartWith($str)
{
    return is_numeric($str[0]) ? 'Number' : 'Letter';
}

echo StartWith('AdamSavior');

Since your task is in database, would be good if it is done with query

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
0

You can use is_numeric() function. Have a look at this link

How can I check if a char is a letter or a number?

0
<?php

function StartWith($str)
{
    if(is_numeric($str[0])) {
        return "Number";

    }else{
        return "Letter";
    }
}
echo StartWith('adamSavior');

Good luck!

Mr Pro Pop
  • 666
  • 5
  • 19