Forum Moderators: coopster

Message Too Old, No Replies

Finding the 2nd, 3rd, 4th etc. phrase in a comma-separated array?

         

internetheaven

2:03 pm on Oct 13, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



If I have an array with:

phrase 1, phrase 2, phrase 3, phrase 4

How do I split it up to have them retrieved individually? I can get phrase 1 okay by searching for the first comma and cutting. But what about the rest?

%%phrase1%% = phrase 1
%%phrase2%% = phrase 2
%%phrase3%% = phrase 3
%%phrase4%% = phrase 4

Help please!

Thanks
Mike

penders

2:14 pm on Oct 13, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If I have an array...


If you have an array, then you simply reference $myarray[0], $myarray[1], etc. to access the 1st, 2nd, etc. element.

But, I assume from the rest of your post that you don't actually have an array... possible a comma separated string?

In which case, make an array from the string by exploding it...

$mystring = 'phrase 1, phrase 2, phrase 3, phrase 4';
$myarray = explode(',',$mystring);
echo $myarray[0]; // phrase 1
echo $myarray[1]; // phrase 2
// etc.


Is the space after the comma delimiter a reality/problem?

omoutop

1:41 pm on Oct 15, 2014 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



use trim() for the space after the comma
echo trim($myarray[0]); // phrase 1

assuming that your extra space is not needed

paulg

10:11 am on Dec 9, 2014 (gmt 0)

10+ Year Member



Use this function
explode() function breaks a string into an array.The "separator" parameter cannot be an empty string.
$mystr='ph1,ph2,ph3';
$myarray=explode(',',$mystr);
echo $myarray[0];
echo $myarray[1];