views:

97

answers:

3

The goal is to count the number of paragraphs in a group of users text...

(I will assume its always bigger than 5 paragraphs for this exercise)

Then I want to 1/2 the number of paragraphs, round it down and enter some content(echo "yehhoo") in between.

I do understand the way I have gotten my $newvalue is not very good, would also like help on that...

<?php

$choppedup = explode("<p>",$node->field_long_body[0]['safe']);
$choppedpos = count($choppedup);
$choppedpos2 = $choppedpos/2;
$newvalue = floor($choppedpos2);

//I know this is working to here... the rest not so sure.

for($j = 0; $j < $choppedup; $j ++):
  print $choppedup[$j];
  if ($j == $newvalue):
    echo "yehhoo" ;       
  endif;
endif;
?>

Thank you

+3  A: 
for 
...
endfor;       # not endif

your $newvalue calculation is not terrible, for the array iteration I'd rather suggest foreach loop (using curly braces):

foreach($choppedup as $ind => $p) {
    echo $p;
    if ($ind == $newvalue) {
        echo 'yehoo';
    }
}
SilentGhost
worked excellent. thank youI will explore the "as" ... thats a new one for sure...
fighella
@fighella: you're welcome to accept my answer if it solves your problem.
SilentGhost
why the downvote?
SilentGhost
Im new at this. I did not downvote .. :) will accept tho. Thanks alot.
fighella
I know you didn't, you can't :) but I'm really curious what I should correct to improve my answer.
SilentGhost
+1  A: 

"Yehhoo" for curly brackets!

for($j == 0; $j < $choppedup; $j ++) {
     print $choppedup[$j];
     if ($j == $newvalue) {
          echo "yehhoo";
     }
}
Mr. Smith
why do some examples use the ":" ... whats the difference there?(ps thank you)
fighella
@fighella: read up on what you're actually using: http://docs.php.net/manual/en/control-structures.alternative-syntax.php
SilentGhost
i guess i did not notice the for and foreach... will pay more attention...
fighella
A: 

Why do such a complex loop to count the number of paragraph tags?

You can do something like this:

 $sInput = '<p>Hello World</p><p>What is going on</p><p>Blah</p>';
 if(preg_match_all('/<p>/', $sInput, $arMatches)!==false)
  print count($arMatches[0]) . ' paragraphs<br/>';

Of course the above needs some work to make sure there are text between the paragraph tags, but this should work for you need.

Daniel
The loop is not complex, but your code indeed is not noob-readable.
Andrejs Cainikovs
Well it is complex for his purpose. You can easily achieve what he's doing simply by using regular expressions. It's easier to maintain and it doesn't require much change if your requirements change.It's not about being "noob friendly" as you put it. The difference here is that the code is too complex for his purpose. Don't try to reinvent the wheel and use what you got.
Daniel