[SOLVED] print first letter of string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
$var
Forum Contributor
Posts: 317
Joined: Thu Aug 18, 2005 8:30 pm
Location: Toronto

[SOLVED] print first letter of string

Post by $var »

how do you trim down the output of a database entry,
like a first name so that instead of

Chris Brown

you'd get either

C. Brown
- or -
C Brown

?
Last edited by $var on Fri Jan 27, 2006 9:36 am, edited 1 time in total.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

First you would have to split up the string (By spaces I believe)

Then, get the first char of the first word:

$var = 'Chris';
$first_letter = $var{0}

Next put the string back together w/o the first word :)
User avatar
Technocrat
Forum Contributor
Posts: 127
Joined: Thu Oct 20, 2005 7:01 pm

Post by Technocrat »

Just as an FYI you can also use substr but hawleyjr's code is faster
User avatar
$var
Forum Contributor
Posts: 317
Joined: Thu Aug 18, 2005 8:30 pm
Location: Toronto

Post by $var »

thanks guys...
both are helpful

i have a question though...

$var{0} : what is this doing?

{0} what is the significance of the 0?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

byte offset zero.
User avatar
$var
Forum Contributor
Posts: 317
Joined: Thu Aug 18, 2005 8:30 pm
Location: Toronto

Post by $var »

i don't suppose there is a stupificated explantion of that... like...
the zero is for this reason, and it is relevant because it can be used in these other ways?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

indexes into strings are zero based, like standard arrays. The zeroth byte is the first byte in the string, followed by the oneth being the second and so forth.
User avatar
$var
Forum Contributor
Posts: 317
Joined: Thu Aug 18, 2005 8:30 pm
Location: Toronto

Post by $var »

thanks feyd. you rock.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

$var wrote:thanks feyd. you rock.

What am I chopped liver? :lol: :lol:


j/k :)
Post Reply