What is wrong with my syntax here? - php

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

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';
}
}

"Yehhoo" for curly brackets!
for($j == 0; $j < $choppedup; $j ++) {
print $choppedup[$j];
if ($j == $newvalue) {
echo "yehhoo";
}
}

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.

Related

PHP even numbers generating

I'm somewhat new to PHP, been reading a few books and I've never seen a loop where it gets you all the even numbers(for example from 1 to 10), so I decided to try it myself:
for($i=0;$i<10 && $i % 2===0;$i++)
echo $i;
Tried with only double == as well.
And this,
$i=0;
do echo $i; while($i++<10 && $i % 2 ==0);
Can't seem to figure out how to use 2 conditions in the same statement.
Would appreciate the help!
Thanks.
Try to use this code
for( $i=0; $i<=10; $i++ )
{
if( $i%2 == 0 ){
echo $i;
}
}
The loop is breaking entirely when the second condition fails the first time. On the first iteration: 0 is less than 10, and it is even, so the loop iterates. On the second iteration: 1 is less than 10, but is odd, so the loop breaks.
Your code is the equivalent of this:
for($i=0; $i<10; $i++) {
if ($i % 2 !==0 ) {
break;
}
echo $i;
}
0
You can eliminate the second condition of your for loop to prevent the breakage and rely exclusive on a third expression to increment $i by two each iteration.
for($i=0; $i<10; $i = $i + 2) {
echo $i;
}
02468
The second statement in a for-loop is/are the condition(s) which gets checked every loop. so if it fails your loop stops. what you need will look somewhat like this:
for ($i = 0; $i < 10; $i++)
if ($i % 2 == 0)
echo $i;
So the loop will run over every number but only print out the even ones.
You don't need to loop.
Range can create a range with third parameter step 2.
$arr = range(0,20,2);
Echo implode(" ", $arr);
https://3v4l.org/S3JWV
you can use also regular loop and get the evens by formula:
for($i=0; $i<10 ;$i++) {
$j = $i * 2;
// do somthing with $j witch loop over 10 first evens...
}

PHP echo line X times different text

Title might not make complete sense, couldn't think of a way to explain it so I will do a mock PHP example.
<?php
$startNumber = 1;
$endNumber = 15;
$fileExt = '.jpg';
?>
And then on the page it will echo from the $startNumber to the $endNumber in something like a foreach
<?php echo("<img src=\"#.jpg\">"); ?>
Hope this is making sense...
I'd also like to point out that the numbers < 10 start with a 0 so it will need to be in the image source link.
echo is not a function, it's a language construct. Don't use ().
Also you need to use a loop like for() to do that (Also see sidenote of Fred -ii).
$endNumber = 15;
for($i = 1; $i <= $endNumber; $i++) {
if($i < 10) {
$i = "0".$i;
}
echo "<img src=\"".$i.".jpg\" />";
}
If this is not what you asked, add more information.

PHP loop X amount of times

I have a string called $columns which dynamically gets a value from 1 to 7. I want to create a loop of <td></td> for however many times the value of $columns is. Any idea how I can do this?
for ($k = 0 ; $k < $columns; $k++){ echo '<td></td>'; }
Here's a more readable way to achieve this:
foreach(range(1,$columns) as $index) {
//do your magic here
}
If you just need to use number of repeat count:
for ($i = 0; $i < 5; $i++){
// code to repeat here
}
just repeat $n times? ... if dont mind that $n goes backwards...
the advantage is that you can see/config "times" at the beginning
$n = 5;
while (--$n >= 0)
{
// do something, remember that $n goes backwards;
}
I like this way:
while( $i++ < $columns ) echo $i;
Just bear in mind if $columns is 5, this will run 5 times (not 4).
Edit: There seems to be some confusion around the initial state of $i here. You are welcome to initialise $i=0 beforehand if you wish. This is not required however as PHP is a very helpful engine and will do it for you automatically (tho, it will throw a notice if you happen to have those enabled).
There is a str_repeat() function in PHP, which repeats a string a number of times. The solution for your problem would be:
str_repeat( '<td></td>', $columns );
If $columns is a string you can cast to int and use a simple for loop
for ($i=1; $i<(int)$columns; $i++) {
echo '<td></td>';
}
A for loop will work:
for ($i = 0; $i < $columns; $i++) {
...
}
You can run it through a for loop easily to achieve this
$myData = array('val1', 'val2', ...);
for( $i = 0; $i < intval($columns); $i++)
{
echo "<td>" . $myData[$i] . "</td>";
}
Why use logic at all, don't waste those CPU cycles!
<td colspan="<?php echo $columns; ?>"></td>

0's Not being Stripped from the front of a numeric value

I am working on a project for a friend's website which is suppose to generate completely random phone numbers to be displayed on a "fake" review board. I figured the best way to do with would be for me to to generate out each section separably. So 3-3-4, but no matter what I do, every time there is a 0 in front the code cuts it off. Here's an example of what I mean:
http://www.shiningashes.net/Test.php
yet this is what I have for the code:
<?php
for ($i = 0000; $i <= 9999; $i++) {
echo $i;
echo "<br>";
}
?>
How do I get the 0's to stop being cropped out so the 0's display? 0001, 0021, 0123, etc?
You can use str_pad
for ($i = 0; $i <= 9999; $i++) {
echo str_pad($i, 4, '0', STR_PAD_LEFT);
echo "<br>";
}
You can use printf to format your output:
<?php
for ($i = 0; $i <= 9999; $i++) {
printf("%04d<br>\n",$i);
}
?>
You need to make your variable a string if you want to keep the zeros. That would mean using quotes, and never using numeric operators on it. But since you depend on using ++ on it, I suggest the following hack:
<?php
for ($i = 10000; $i <= 19999; $i++) {
$str=substr ( $i , 0 , 4 );
echo $i;
echo $str;
echo "<br>";
}
?>
You will need to convert your integer to a string when printing it.
<?php
for ($i = 0; $i <= 9999; $i++) {
printf("%04d<br />", $i);
}
?>
Check the documentation for printf/sprintf for more information.
Kind regards,
Stefan

issue in printing dimension of numbers php

I am just a beginner in PHP. I am trying to write program to print numbers like following.
1 1
12 21
123 321
1234 4321
1234554321
I have written the following code.
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
echo "<br />";
for($j=1; $j<=$i; $j++)
{
echo $j;
}
}
?>
The result displays the following.
1
12
123
1234
12345
I could not reverse it like
1
21
321
4321
54321
How can I do this?
The simplest, hard coded version:
<?php
$text = "1 1
12 21
123 321
1234 4321
1234554321";
echo $text;
?>
Edit
A more generic solution:
<?php
$n = 5;
$seq1 = '';
$seq2 = '';
$format1 = sprintf("%%-%su", $n); //right justified with spaces
$format2 = sprintf("%%%su", $n); //left justified with spaces
for($i=1; $i<=$n;$i++){
$seq1 .= $i;
$seq2 = strrev($seq1);
echo sprintf("$format1$format2\n", $seq1, $seq2);
};
?>
Okay. What you wrote is pretty good. There need to be several changes in order to do what you wanted though. The first problem is that you are rendering it to HTML - and HTML does not render spaces (which we'll need). Two solutions: you use for space, and make sure you use a proportional font, or you wrap everything into a <pre> tag to achieve pretty much the same thing. So, echo "<pre>"; at the start, echo "</pre>"; at the end.
Next - don't have the inner loop go to $i. Let it go to 5 every time, and print a number if $j <= $i, and a space otherwise.
Then, right next to this loop, do another one, but in reverse (starting with 5 and ending with 1), but doing the very same thing.
Viola is a musical instrument.
Here is my solution to your problem.
It isn't the best solution because it doesn't take into account that you could be using numbers higher than 9, in which case it will push the numbers out of line with each other.
But the point is that it is still the start of a solution that you could work on if needed.
You can use an array to store the numbers you want to print.
Because the numbers are in an array it means we can just use a foreach loop to make sure all of the numbers get printed.
You can use PHP's str_repeat() function to figure out how many spaces you need to put in between each string of numbers.
The below solution will only work if you use an array with the default number indicies as opposed to an associative array.
This is because it uses the $key variable in part of the calculation for the str_repeat() function.
If you would rather not use the $key variable then you should be able to figure out how to change that.
When it come to reversing the numbers they have already been stored in a string so you can just use PHP's strrev() function to take care of that and store them in another variable.
Finally you just have to print a line to the document with a line break at the end.
Note that the str_repeat() function is repeating the HTML entity.
This is because the browser will just compress normal white space down to 1 character.
Also note that I have included a style block to change the font to monospace.
This is to ensure that the numbers all line up with each other.
<style>
html, body {
font: 1em monospace;
}
</style>
<?php
$numbers = array(1, 2, 3, 4, 5);
$numbers_length = count($numbers);
$print_numbers = '';
$print_numbers_rev = '';
foreach($numbers as $key => $value) {
$spaces = str_repeat(' ', ($numbers_length - ($key + 1)) * 2);
$print_numbers .= $value;
$print_numbers_rev = strrev($print_numbers);
echo $print_numbers . $spaces . $print_numbers_rev . '<br />';
}
Edit:
Solution without array:
<style>
html, body {
font: 1em monospace;
}
</style>
<?php
$numbers = 9;
$numbers_length = $numbers + 1;
$print_numbers = '';
$print_numbers_rev = '';
for($i = 0; $i <= $numbers; ++$i) {
$spaces = str_repeat(' ', ($numbers_length - ($i + 1)) * 2);
$print_numbers .= $i;
$print_numbers_rev = strrev($print_numbers);
echo $print_numbers . $spaces . $print_numbers_rev . '<br />';
}
$n = 5;
for ($i = 1; $i <= $n; $i++) {
$counter .= $i;
$spaces = str_repeat(" ", ($n-$i)*2);
echo $counter . $spaces . strrev($counter) . "<br/>";
}
<div style="position:relative;width:100px;height:auto;text-align:right;float:left;">
<?php
$n=5;
for($i=1; $i<=$n; $i++)
{
echo "<br />";
for($j=1; $j<=$i; $j++)
{
echo $j;
}
}
?>
</div>

Categories