issue in printing dimension of numbers php - 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>

Related

Remove the 0 from for results

Currently, I'm messing around with SoundCloud's API and it's returning something that looks like this.
0. HotBox Michael da Vinci Prod Free P.mp3
https://api.soundcloud.com/tracks/373337717/stream?client_id=OURID
1. LSSR Chris P Prod Jake Knight.mp3
https://api.soundcloud.com/tracks/373336760/stream?client_id=OURID
Which is working properly as how the code appears, here it is how I'm printing out the results (very messy but I'm just messing around)
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
print '<br>'; print '<br>';
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
print ''.$i.'. '.$title.'.mp3';
print '<br>';
print $stream = ''.$b2.'?client_id=OURID';
}
Now what I'm wondering is how under every circumstance can we make the 0. return as a 1. and continue counting upwards until reaching the end of the for loop, not removing the 0. data but only changing the number.
I recommend a foreach loop with the $i counter declared in the loop and just increment it as you go.
Untested code:
foreach ($house as $i=>$row){
echo '<br><br>',++$i,'. ',preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title'])),".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
p.s. I've improved the regex pattern and eliminated all single-use variable declarations. You can break this up over many lines if you prefer.
If you want to avoid the first iteration's double break tags...
foreach ($house as $i=>$row){
if($i) echo '<br><br>'; // if $i is not 0
echo ++$i,'. ';
echo preg_replace ('/[^a-z\d\s]+/i','',strip_tags ($row ['title']));
echo ".mp3<br>{$row ['stream_url']}?client_id=OURID";
}
Based on the comments and your description of what you are trying to do, it sounds like you just need to add another iteration variable:
# Add another variable
$a = 1;
for ($i = 0; isset($house[$i]); $i++) {
$b1 = $house[$i]['title'];
$b2 = $house[$i]['stream_url'];
$title = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($b1));
echo '<br><br>';
# Here you have the $a show up starting at 1
echo ''.$a.'. '.$title.'.mp3<br>';
echo $stream = ''.$b2.'?client_id=OURID';
# Auto increment here
$a++;
}

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

PHP function to loop thru a string and replace characters for all possible combinations

I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.
I want it to be able to go through all the possible combinations for the given string, for example:
go one-by-one
then combo i.e.. 2 at a time, then three at a time, till you get length at a time
then start in combo split, i.e.. first and last, then first and second to last
then first and last two, fist and second/third last
So for the characters "abcd" it would return:
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
etc.......... so on and so forth till there are no other combinations
Any ideas, or has anyone seen a function somewhere I could modify for this purpose?
loop from 0 to 2^length - 1. On each step, if Nth bit of the loop counter is 1, encode the Nth character
$str = 'abcd';
$len = strlen($str);
for($i = 0; $i < 1 << $len; $i++) {
$p = '';
for($j = 0; $j < $len; $j++)
$p .= ($i & 1 << $j) ? '&#' . ord($str[$j]) . ';' : $str[$j];
echo $p, "\n";
}
There are 2^n combinations, so this will get huge fast. This solution will only work as long as it fits into PHP's integer size. But really who cares? A string that big will print so many results you'll spend your entire life looking at them.
<?php
$input = 'abcd';
$len = strlen($input);
$stop = pow(2, $len);
for ($i = 0; $i < $stop; ++$i)
{
for ($m = 1, $j = 0; $j < $len; ++$j, $m <<= 1)
{
echo ($i & $m) ? '&#'.ord($input[$j]).';' : $input[$j];
}
echo "\n";
}
How about this?
<?php
function permutations($str, $n = 0, $prefix = "") {
if ($n == strlen($str)) {
echo "$prefix\n";
return;
}
permutations($str, $n + 1, $prefix . $str[$n]);
permutations($str, $n + 1, $prefix . '&#' . ord($str[$n]) . ';');
}
permutations("abcd");
?>

stuck here with lotto grid

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>";

What is wrong with my syntax here?

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.

Categories