...

View Full Version : foreach on string



manhood
06-22-2010, 11:58 AM
I would like to do a foreach on this string:

$mystring="item1, item9, item7, item3, item2, item6, item8";

I don't know how to do this though. Hope someone can help me

Dormilich
06-22-2010, 12:12 PM
if you want to get each "item", explode() by ", ".

johnduarte
06-22-2010, 07:55 PM
I would like to do a foreach on this string:

$mystring="item1, item9, item7, item3, item2, item6, item8";

I don't know how to do this though. Hope someone can help me


$mystring="item1, item9, item7, item3, item2, item6, item8";
$myArray= explode(", ", $mystring);
foreach($myArray as $key => $value){
echo "item: $value<br />";
}

Keleth
06-22-2010, 08:25 PM
I'd use single quotes as they're faster, but meh :-P

Just as an explanation: foreach is used to cycle through an array. Using explode, you can separate a string into an array based on whatever element you're exploding on (', ' in this case). You can then feed that array through foreach. You can also use the shorthand foreach in this case, as the key's don't matter:


foreach ($myArray as $value) {
//whatever
}

johnduarte
06-22-2010, 08:37 PM
I'd use single quotes as they're faster, but meh :-P

Just as an explanation: foreach is used to cycle through an array. Using explode, you can separate a string into an array based on whatever element you're exploding on (', ' in this case). You can then feed that array through foreach. You can also use the shorthand foreach in this case, as the key's don't matter:


foreach ($myArray as $value) {
//whatever
}

Yes, "Best Practice" is to use single quotes when you can, but it isn't noticeably faster till you hit millions of iterations, and even then it's only fractions of a second faster. So "best practice" but not something you should worry about and go back and change old code to fix.

Keleth
06-22-2010, 08:46 PM
Yes, "Best Practice" is to use single quotes when you can, but it isn't noticeably faster till you hit millions of iterations, and even then it's only fractions of a second faster. So "best practice" but not something you should worry about and go back and change old code to fix.

Hehe, its why I put the silly smilie after. I didn't mean to hit a chord, was just joking around.

johnduarte
06-22-2010, 08:54 PM
Hehe, its why I put the silly smilie after. I didn't mean to hit a chord, was just joking around.

no chord hit, was just clarifying so someone reading it didn't think they should go back and fix all previous code hoping to show vast improvement in speed.

Keleth
06-22-2010, 09:02 PM
no chord hit, was just clarifying so someone reading it didn't think they should go back and fix all previous code hoping to show vast improvement in speed.

Oh good god no, yah, its fractions of a second if even. Its a lot about personal taste and purpose too (I don't like having to escape double quotes :p)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum