String problem

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
leewad
Forum Commoner
Posts: 91
Joined: Tue May 11, 2004 8:32 am

String problem

Post by leewad »

Hi

How would I get the first and last value from an string?

I have a string with the following:

Code: Select all

$sizes= "7,8,9,10.5,11,11.5,12";
How can i seperate the string so it display sizes = 7-12 ?

Thanks
Charles256
DevNet Resident
Posts: 1375
Joined: Fri Sep 16, 2005 9:06 pm

Post by Charles256 »

off the top of my head use the implode function, where the seperator is a comma, then use array sort to get it in ascending order. then use count on the array to figure out how many elements and then last but not least display array_element[0] (the smallest size) and array_element[n-1] where n is the size of the array.pseudo code below..

Code: Select all

$array=implode(",",$my_String);
$count=count($array);
$array=sort($array);
$n=$count-1;
echo "$array[0] - $array[$n]";
something like that should do nicely. :-D
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

With strpos you can determine the first and last occurence of ','. And with substr you can get substrings (parts) of a string...
leewad
Forum Commoner
Posts: 91
Joined: Tue May 11, 2004 8:32 am

Post by leewad »

Thanks but I used the follow:

Code: Select all

$sizes= "7,8,9,10.5,11,11.5,12";
$sizes=explode(",",$sizes);
echo $sizes[0]." - ".array_pop($sizes);
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

I would do it like this:

Code: Select all

$sizes =  '7,8,9,10.5,11,11.5,12';
echo $sizes{0} . ' - ' . substr($sizes, -1, 1);
leewad
Forum Commoner
Posts: 91
Joined: Tue May 11, 2004 8:32 am

Post by leewad »

But that would only give you 7 - 2
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Sorry, my mistake. Just do it with the array :wink:
Post Reply