primetime Posted August 7, 2011 Share Posted August 7, 2011 Hi all, have just bought Larry's book PHP for the Web Visual Quickstart Guide 4th Ed and have been struggling with the following: - How do I convert every other word in a string so that it is emphasized? I have tried the explode PHP function and using the FOR loop with it but it outputs only every second word. What is needed eg is: This is every other word that is emphasized. Any help would be greatly appreciated. Link to comment Share on other sites More sharing options...
Stuart Posted August 7, 2011 Share Posted August 7, 2011 $string = 'the quick brown fox jumps over the lazy dog'; $words = explode(' ', $string); $emphasise = FALSE; foreach($words as $key => $word){ if ($emphasise){ $words[$key] = '<strong>' . $word . '</strong>'; } $emphasise = !$emphasise; } echo implode(' ', $words); 1 Link to comment Share on other sites More sharing options...
zanimation Posted August 7, 2011 Share Posted August 7, 2011 $string = 'the quick brown fox jumps over the lazy dog'; $words = explode(' ', $string); $emphasise = FALSE; foreach($words as $key => $word){ if ($emphasise){ $words[$key] = '<strong>' . $word . '</strong>'; } $emphasise != $emphasise; } echo implode(' ', $words); Since != is a comparison operator(not an assignment operator), you'll want to change: $emphasise != $emphasise; to $emphasise = !$emphasise; Also, here's an alternate modified version of Stuart's code which avoids the need for conditional checks and an extra variable: $string = 'the quick brown fox jumps over the lazy dog'; $words = explode(' ', $string); for($i = 1; $i < count($words); $i += 2) { $words[$i] = '<strong>' . $words[$i] . '</strong>'; } echo implode(' ', $words); If you're going to be using it frequently throughout your code, here's a functionalized form: function emphAltern($string, $start = 1) { $words = explode(' ', $string); for($i = $start; $i < count($words); $i += 2) { $words[$i] = '<strong>' . $words[$i] . '</strong>'; } return implode(' ', $words); } Link to comment Share on other sites More sharing options...
Stuart Posted August 7, 2011 Share Posted August 7, 2011 Haha oops code amended thanks for spotting that one. Link to comment Share on other sites More sharing options...
primetime Posted August 7, 2011 Author Share Posted August 7, 2011 Many thanks to Stuart and zanimation. Besides the great replies, it also shows there are still a lot I have to learn about PHP and there are many alternate solutions! Thanks again. Link to comment Share on other sites More sharing options...
Recommended Posts