I think this might be an easy question for the professionals out there, but here goes.
Basically I want to get the total word count of a bunch of paragraphs. Right now I can get the word count of each paragraph, but I can't figure out how to add them all up.
$para // an array of paragraph strings
$totalcount = '';
foreach ($para as $p)
{
$count = str_word_count($p, 0);
echo $count . "<br />";
}
print_r($totalcount);
this prints a list of 41 numbers, representing the word count of each pagraphs
but the $totalcount is an array of all these numbers. How can I get the sum of all 41 paragraphs?
$totalcount = 0;
foreach(...) {
$totalcount += $count;
}
echo $totalcount;
You need to add to the total count each loop:
$para // an array of paragraph strings
$totalcount = 0;
foreach ($para as $p)
{
$count = str_word_count($p, 0);
echo "Count: ".$count . "<br />";
$totalcount += $count;
}
echo "Total Count: ".$totalcount;
Related
I'm stuck trying to use nested loops to make a reflective pattern from numbers.
I've already tried, but the output looks like this:
|0|1|2|
|0|1|2|
|0|1|2|
This is my code:
<?php
echo "<table border =\"1\" style='border-collapse: collapse'>";
for ($row=1; $row <= 3; $row++) {
echo "<tr> \n";
for ($col=1; $col <= 3; $col++) {
$p = $col-1;
echo "<td>$p</td> \n";
}
echo "</tr>";
}
echo "</table>";
?>
I expected this result:
|0|1|0|
|1|2|1|
|0|1|0|
Each columns' and rows' cell values must increment to a given amount then decrement to form a mirror / palindromic sequence.
First declare the square root of the of the table cell count. In other words, if you want a 5-by-5 celled table (25 cells), declare $size = 5
Since your numbers are starting from zero, the highest integer displayed should be $size - 1 -- I'll call that $max.
I support your nested loop design and variables are appropriately named $row and $col.
Inside of those loops, you merely need to make the distinction between your "counters" as being higher or lower than half of the $max value. If it is higher than $max / 2, you subtract the "counter" (e.g. $row or $col) from $max.
By summing the two potentially adjusted "counters" and printing them within your inner loop, you generate the desired pattern (or at least the pattern I think you desire). This solution will work for $size values from 0 and higher -- have a play with my demo link.
Code: (Demo)
$size = 5;
$max = $size - 1;
echo "<table>\n";
for ($row = 0; $row < $size; ++$row) {
echo "\t<tr>";
for ($col = 0; $col < $size; ++$col) {
echo "<td>" . (($row >= $max / 2 ? $max - $row : $row) + ($col >= $max / 2 ? $max - $col : $col)) . "</td>";
}
echo "</tr>\n";
}
echo "</table>";
Output:
<table>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>2</td><td>3</td><td>4</td><td>3</td><td>2</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>2</td><td>1</td></tr>
<tr><td>0</td><td>1</td><td>2</td><td>1</td><td>0</td></tr>
</table>
There are a lot of ways to achive that.
An easy way to do that is;
<?php
$baseNumber = 0;
echo "<table border='1' style='border-collapse: collapse'>";
for ($row = 0; $row < 3; $row++) {
echo "<tr>";
if ($row % 2 !== 0) {
$baseNumber++;
} else {
$baseNumber = 0;
}
for ($col = 0; $col < 3; $col++) {
echo "<td>" . ($col % 2 === 0 ? $baseNumber : $baseNumber + 1) . "</td>";
}
echo "</tr>";
}
echo "</table>";
this code will do what you want just call the patternGenerator function with the number of distinct numbers you want for your example these numbers are 3 (0,1,2).
the idea in this code is to use two for loops one that starts from the minimum number to the maximum one and the other one that starts after the maximum number decreasing to the minimum.
for example:
if min = 0 and max = 5
the first loop will print 0,1,2,3,4,5
and the second will print 4,3,2,1,0
and that's it.
at first, I created a function that creates just on row called rowGenerator it takes $min and $max as parameters and prints one row
so if we want to print a row like this: |0|1|0| then we will call this function with min = 0 and max = 1 and
if we want to print a row like this: |1|2|1| then we will call it with min = 1 and max = 2.
function rowGenerator($min, $max)
{
echo '<tr>';
for($i = $min; $i<=$max;$i++)
echo '<td>'.$i.'</td>';
for($i = $max-1; $i>=$min;$i--)
echo '<td>'.$i.'</td>';
echo '</tr>';
}
for now, we can print each row independently. now we want to print whole the table if we look at the calls we do for the rowGenerator function it will looks as follow:
(min = 0, max = 1),
(min = 1, max = 2) and
(min = 0, max = 1).
minimums are (0,1,0).
yes, it's the same pattern again. then we need two loops again one to start from 0 and increase the number until reach 1 and the other one to loop from 0 to 0.
and that's what happened in the patternGenerator function. when you call it with the number of distinct numbers the function just get the min that will always be 0 in your case and the max.
function patternGenerator($numberOfDistinct )
{
echo "<table border =\"1\" style='border-collapse: collapse'>";
$min = 0;
$max = $numberOfDistinct - 2;
for($i = $min;$i<=$max; $i++)
{
rowGenerator($i,$i+1);
}
for($i = $max-1;$i>=$min;$i--)
{
rowGenerator($i,$i+1);
}
echo '</table>';
}
this is the output of calling patternGenerator(3):
the output of calling patternGenerator(5):
I have an ordered list which is 19 entries long (but could change and be more or less). I'm listing it on a drop down menu but because of its length the column is dropping below the fold of the page.
I'd like to create a separate column (ul or div) to either divide the list into 2 or 3 equally, or have set list sizes e.g. max 7 per list.
Any ideas? Current code:
<div id="colour" class="dropmenudiv">
<?php
$sql = "select * from rug_colours where id <> 0 and active = 1 order by name";
$rs = $database->query($sql);
$index = 0;
foreach($rs as $v) {
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
}
?>
Try something along the lines of:
<div id="colour" class="dropmenudiv">
<?php
$sql = "select * from rug_colours where id <> 0 and active = 1 order by name";
$rs = $database->query($sql);
$column_height = 7;
echo "<div class='column'>";
foreach($rs as $idx => $v) {
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
if($idx % $column_height) echo "</div><div class='column'>";
}
echo "</div>";
?>
and for equal split you might try this:
$max_column_height = 7;
$no_of_cols = ceil(count($rs) / $max_column_height);
$column_height = floor($count($rs) / $no_of_cols);
You should use index variable to divide it into 2 or 3 div.
Following is example to make it in three parts:
$index = 0;
foreach($rs as $v) {
if($index > 7){
$index = 0; // reset to zero. You can also seperate it by any tag div or ul if you want
}
echo "<a href=\"//$base_url/?action=search&colour=".$v['id']."\" >".$v['name']."</a>";
$index++;
}
For an evenly spread distribution, first divide the number of elements by 7 (or whichever maximum rows you want to allow), rounding upwards. This gives the number of columns. Then divide the number of elements by the number of columns, rounding upwards: this gives you the actual number of rows you need.
I like array_chunk for this purpose:
$maxRowCount = 7;
$colCount = ceil(count($rs) / $maxRowCount);
$chunkSize = ceil(count($rs) / $colCount);
foreach(array_chunk($rs, $chunkSize) as $column) {
echo "<div class='column'>\n";
foreach($column as $v) {
echo "<a href=\"//$base_url/?action=search&colour={$v['id']}\" >{$v['name']}</a>";
}
echo "</div>\n";
}
You can create array of columns based on current index in foreach() loop like
$abc = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
$cols = [];
$perCol = 7;
foreach($abc as $index => $val) {
$colInd = $index / $perCol;
$cols[$colInd][] = $val;
}
print_r($cols);
This will split data in $abc into 3 coluns by 7 items per column.
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>
I have a grid with 42 nrs where I will use the rand() function to pick out numbers from the grid and and mark them
so far I came up with
<?php
$row="";
print ("<table border=\"1\">");
for ($i=0; $i<6; $i++)
{
print ("<tr>");
for ($j=0; $j<7; $j++)
{
$random = rand(1,42);
$row += "(string)$random";
$som = $som + 1;
print("<th>".$som);
}
("</tr>");
}
print ("</table>");
print ("$rij");
// here I'm just testing to see if I can get a list of random numbers
for ($i=0; $i<6; $i++){
$randomNr = rand(1,42);
echo "$randomNr<br/>";
}
?>
I guess the idea is to match the numbers out of the rand function to the indexes of the table. But i'm really stuck here at getting the table to convert to an arra so I can match the index with the random numbers.
You're probably not too far off with your own attempt. You would just need to generate 6 random unique numbers and compare against them. Easiest way to do that is to generate an array using range() and pick the random numbers with array_rand() (which actually returns indexes, so you need a bit of additional code to get the values). Then you just need to find whether the currently outputted number is in the chosen number array using in_array()
Here's an example function of the general case that expands Sondre's example a bit. The function in the example takes following arguments: Total random numbers picked, Smallest number in the grid, Biggest number in the grid and the numbers per row in the grid. The function returns the generated HTML table source a string.
<?php
function generateHighlightedLotteryTable ($count = 6, $min = 1, $max = 42, $perRow = 7)
{
// Generate the picked numbers (actually we just get their indexes)
$nums = array_rand(range($min, $max), $count);
$output = "<table>\n";
for ($n = $min; $n <= $max; $n++)
{
// get "index" of the number, i.e. $min is the first number and thus 0
$i = $n - $min;
if ($i % $perRow == 0)
{
$output .= "<tr>";
}
// If the current number is picked
if (in_array($i, $nums))
{
$output .= "<td><strong>$n</strong></td>";
}
// If the current number hasn't been chosen
else
{
$output .= "<td>$n</td>";
}
if ($i % $perRow == $perRow - 1)
{
$output .= "</tr>\n";
}
}
// End row, if the numbers don't divide evenly among rows
if (($n - $min) % $perRow != 0)
{
$output .= "</tr>\n";
}
$output .= "</table>";
return $output;
}
echo generateHighlightedLotteryTable();
?>
I hope this is what you were trying to achieve.
This would create a grid of 42 numbers and mark out a random one. If you want to mark out more create and array and check against that insted of just the rand variable. In you're original code there you were actually running the rand-function 42 times which I guess is unintended.
EDIT: Or did you need the grid to be filled with random numbers?
$rand = rand(1, 42);
echo "<table>";
for($i = 1;$i <= 42; $i++) {
if($i%7 == 1) {
echo "<tr>";
}
$print = $rand == $i ? "<strong>" . $i . "</strong>" : $i;
echo "<td>" . $print . "</td>";
if($i%7 == 0) {
echo "</tr>";
}
}
echo "</table>";
I have this PHP loop,
foreach($returnedContent as $k => $v) {
$imageName = str_replace($replaceData, "", $v['contentImageName']);
echo "<a class='contentLink' href='".base_url()."welcome/getFullContent/$v[contentId]'>";
echo "<img src='/media/uploads/".strtolower($v['categoryTitle'])."/".$imageName."_thumb.png' alt='$v[contentTitle]' />";
echo "</a>";
}
Once the lopp has finished I was hoping it would be possible to do loop to print x amount of grey boxes is this possible and if so how, basically if the first loop returns 1 item i need the second loop to print out 11 boxes, if the first one returns 9 items I need the second loop to return 3 boxes.
Make sense? Can anyone help me?
So if you want a total of 12 boxes, set a counter and decrement:
$boxes = 12;
foreach($returnedContent as $k =>$v){
// all your previous stuff
$boxes--;
}
for($i = 0; $i < $boxes; $i++){
// print your box here
}
Depending on your application you may also want to check that the number of items in $returnContent is <= $boxes. If it is greater than $boxes you won't get an error but you will get rows with more than $boxes images.
Just keep a counter and increment it for each loop iteration, then add
for (;$counter < 11; ++$counter) {
do_loop_stuff();
}
Maybe you could do something like this (assuming $returnedContent is numerically indexed):
//count to 12 so we get 12 items
for ($i=0; $i<12; $i++) {
//check if there is an entry to print
if (isset($returnedContent[$i])) {
$v = $returnedContent[$i];
$imageName = str_replace($replaceData, "", $v['contentImageName']);
echo "<a class='contentLink' href='".base_url()."welcome/getFullContent/$v[contentId]'>";
echo "<img src='/media/uploads/".strtolower($v['categoryTitle'])."/".$imageName."_thumb.png' alt='$v[contentTitle]' />";
echo "</a>";
} else {
//draw grey box
}
}
After the first loop, you can do:
for($i = 0; $i < 12 - count($returnedContent); $i++)
{
// print the grey boxes.
}
Hmmm Im not sure Im understanding you but
$c = count($returnedContent);
will get you the amount of items in the variable
then:
$c = (11-$c);
if($c > 0) {
for($i=0;$i<$c;$i++) {
// print gray box
}
}
after the first loop. You could also use a counter variable inside the first loop.
I did interpret the question as "Do something when the loop has finished iterating".
In which case a for/foreach loop isn't the best choice here.
how about
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
//then do whatever else you need to.
?>