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
leewad
Forum Commoner
Posts: 91 Joined: Tue May 11, 2004 8:32 am
Post
by leewad » Sat May 20, 2006 3:31 am
Hi
How would I get the first and last value from an string?
I have a string with the following:
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 » Sat May 20, 2006 3:44 am
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.
timvw
DevNet Master
Posts: 4897 Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium
Post
by timvw » Sat May 20, 2006 4:04 am
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 » Sat May 20, 2006 4:51 am
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);
Oren
DevNet Resident
Posts: 1640 Joined: Fri Apr 07, 2006 5:13 am
Location: Israel
Post
by Oren » Sat May 20, 2006 5:39 am
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 » Sat May 20, 2006 5:45 am
But that would only give you 7 - 2
Oren
DevNet Resident
Posts: 1640 Joined: Fri Apr 07, 2006 5:13 am
Location: Israel
Post
by Oren » Sat May 20, 2006 5:53 am
Sorry, my mistake. Just do it with the array