<PHP> How to make echo stay on the page permanently with sessions? - php

I have code, which is supposed to echo if it's true.
I did this with an if, but every time I run the code it will replace the previously echo'd number.
Can I make it so echo doesn't replace the past echo, but add an additional $i every time I run the code?
$i = $_SESSION["priem"];
$i++;
$aantaldelers = 2;
for ($j = 2; $j < $i; $j++) {
if ($i%$j == 0) {
$aantaldelers++;
}
}
if ($aantaldelers == 2) {
echo "$i, ";
}
$aantaldelers = 2;
$_SESSION["priem"] = $i;

yes you can do it by adding a string in session same as variable
$i = $_SESSION["priem"];
$i++;
$str = isset($_SESSION["str"]) ? $_SESSION["str"] : ''; //my changes
$aantaldelers = 2;
for ($j=2; $j<$i; $j++)
if ($i%$j == 0)
$aantaldelers++;
if ($aantaldelers == 2) {
$str .= "$i, "; //my changes
echo $str; //my changes
}
$aantaldelers = 2;
$_SESSION["priem"] = $i;
$_SESSION["str"] = $str; //my changes

Related

Display result after each loop

In the code below, a url variable is increasing by 1 every time in a while loop. When $i is equal to 1000, the loop will end and $i will be displayed (from 1 all the way to 1000).
How do I display the value of $i after every loop, rather than waiting to the end?
$i = 1;
while($file = file_get_contents('http://example.com?id='.$i)) {
if($i !== 1000) {
echo $i;
}else{
break;
}
$i++;
}
You will need to flush message after each iteration. That way your browser will receive part of the information even if your request/response is still pending.
ob_implicit_flush(true);
$i = 1;
while($file = file_get_contents('http://example.com?id='.$i) && $i < 1000)
{
echo $i;
$i++;
ob_flush();
flush();
}
ob_end_flush();
Move echo $i; outside of the if() statement:
$i = 1;
while($file = file_get_contents('http://example.com?id='.$i)) {
if($i !== 1000) {
// echo $i;
}else{
break;
}
echo $i;
$i++;
}
This scenario is surely better suited for for() loop instead of while()...
PHP happen on the server. To see each value for $i immediately you would need to make the server:
do it's thing -> display that thing -> reload.
you can reload with header() but that is limited to 20 reloads (I think) unless you use header("Refresh:0");
I would make it display by making a stacking condition.
if(isset($diplay)){//2+ times through
$display = $display . $i . "<br>";
}else{//first time through
$diplay = $i."<br>";
}
then put that inside your condition
if($i !== 1000) {
if(isset($diplay)){
$display = $display . $i . "<br>";
}else{
$diplay = $i."<br>";
}
}else{
break;
}
echo $display
echo $display;
Then increment your variable
$i++;
then refresh page and pass the variable at the same time.
header("Refresh:0; url=page.php?i=$i");
then you'll have to add a condition at the beginning that gets $i or assign it if not found.
if(isset($_GET['i'])){//meaning if it's found in the url like so ?i=$i
$i = $_GET['i'];
}else{//first time through
$i = 1;
}
///////////////////putting it all together////////////////////////
if(isset($_GET['i'])){
$i = $_GET['i'];
}else{
$i = 1;
}
while($file = file_get_contents('http://example.com?id='.$i)) {
if($i !== 1000) {
if(isset($diplay)){
$display = $display . $i . "<br>";
}else{
$diplay = $i."<br>";
}
}else{
break;
}
echo $display;
$i++;
header("Refresh:0; url=page.php?i=$i");
}

how to print this pattern in php?

I run this program, but I need the output within table. So would you please solve this?
<?php
$s="*";
for($b=1; $b<=5; $b++) {
for($c=5; $c>=$b-1; $c--) {
if($c>=$b) {
echo $s;
}
else if($b != 1) {
echo " ";
}
}
for($d=5; $d>=$b; $d--) {
echo $s;
}
echo "<br/>";
}
?>
If you're fine regardless of how the code was written (only results matter), you can use this:
print('<table>');
for ($i = 0; $i < 5; $i++)
{
print('<tr>');
for ($j = 1; $j <= 5; $j++)
{
print('<td>');
(5 - $i >= $j) ? print('*') : '';
print('</td>');
}
for ($j2 = 1; $j2 <= 5; $j2++)
{
print('<td>');
(1 + $i <= $j2) ? print('*') : '';
print('</td>');
}
print('</tr>');
}
print('</table>');
What I did there is I sliced table in half vertically and used 2 for loops to fill left and right halfs. You will get something like this:

Hackerrank draw a staircase of length N in php

Draw a staircase of height N like this:
#
##
###
####
#####
######
Staircase of height 6, note the last line should have zero spaces.
My solution does not work correctly
function draw($size)
{
for ($i = 1; $i <=$size ; $i++)
{
$spaces = $size-$i;
while ($spaces)
{
echo " ";
$spaces--;
}
$stairs = 0;
while ($stairs < $i)
{
echo "#";
$stairs++;
}
echo "<br/>";
}
}
draw(6);
//output
#
##
###
####
#####
######
It is not printing the spaces, I tried \n, PHP.EOL still it didn't work. Any suggestions?
Although other solutions are all good , here is my code as well.
$max=5;
for ( $i =1 ; $i<=$max;$i++) {
for ( $space = 1; $space <= ($max-$i);$space++) {
echo " ";
}
for ( $hash = 1; $hash <= $i;$hash ++ ) {
echo "#";
}
echo "\n";
}
//PHP
$n = 6; // Number of rows.
for($i=1;$i<=$n;$i++){
echo str_repeat(' ', $n-$i) . str_repeat('#', $i);
echo '\n';
}
for(var i = 0; i < n; i++)
{
var s = "";
for(var j = 0; j < n; j++)
{
if(n - i - 2 < j)
{
s += "#";
}
else
{
s += " ";
}
}
console.log(s);
}
for ($i=0; $i<$n; $i++){
for ($j=0; $j<$n; $j++){
if($i+$j>$n-2){
echo "#";
} else {
echo " ";
}
if($j==$n-1 && $i+$j<$n*2-2){ //The second part is to dont break the last line
echo "\n";
}
}
}
Here's another solution:
$int = 7;
for($i = 1; $i<=$int; $i++){
printf('%1$s%2$s%3$s',str_repeat(" ",$int-$i),str_repeat("#",$i),"\n");
}
From official PHP documentation:
str_repeat
$n = 6;
for ($i = 0; $i < $n; $i++) {
$pad = 1;
for ($space = 0; $space < $n-$i-1; $space++) {
$pad++;
}
echo str_pad('#', $pad,' ',STR_PAD_LEFT);
for ($j = 0; $j < $i; $j++) {
echo '#';
}
echo '<br>';
}
Took me a while but finally I manage to do it following OFC (A. Sharma) Example.
<?php
$handle = fopen("php://stdin","r");
$n = intval(fgets($handle));
for ($rows = 0; $rows < $n; $rows++) {
for ($columns = 0; $columns < $n - $rows - 1; $columns++) {
echo " ";
}
for ($columns = 0; $columns < $rows + 1; $columns++) {
echo "#";
}
echo "\n";
}
?>
Use PHP functions range() and str_repeat() for an elegant solution:
function staircase($n){
foreach (range(1, $n) as $i)
print( str_repeat(' ',$n-$i).str_repeat('#',$i)."\n");
}
demo
Check if n is between 0 and 101 ( 0 < n <= 100)
Loop through each row
2.1 print spaces according to the last item position
2.2 print the items
Separate rows
The code below explains everything...
function staircase($n) {
// check if n is between 0 and 101 (0 < n <=100)
if( 0 < $n && $n > 100 ) {
} else {
// Loop through each row
for($i = 1; $i <= $n; $i++) {
// print spaces according to the last item position
$si = 1;
while( $si <= ($n - $i)){
print(" ");
$si++;
}
// print the items
for($j = 1; $j <= $i; $j++) {
print("#");
}
// separate rows
print("\n");
}
}
}
Output: For n = 6
#
##
###
####
#####
######
After playing around with the code and trying/failing couple of times I finally got it right. Notice how in order to print the space and new line I am using "\n". Previous "<br/>" and " " for space didn't work.
Break line will come out of the loop every row number. So if we have $n=4 then every 4 spaces after break line will be echoed.
I have made 2 loops to fill in all fields in the staircase.
The tricky part here is to have them right aligned. This is where if statement comes in place.
Reference link:
Hackerrank Challenge
// Complete the staircase function below.
function staircase($n) {
for($i=1; $i<=$n; $i++){
for($j=1; $j <= $n; $j++){
if( ($n - $i) < $j ){
echo "#";
}else{
echo " ";
}
}
echo "\n";
}
}
Try This
$n=6;
for($i=1;$i<=$n;$i++){
for($spaces=1;$spaces<=($n-$i);$spaces++){
echo " ";
}
for($staires=0;$staires<$i;$staires++){
echo "#";
}
echo "\n";
}
This worked for me
$n = 6;
function staircase($n) {
for($i=1; $i <= $n; $i++){
for($j=1; $j <= $n; $j++){
if($j > $n-$i){
echo "#";
}else{
echo " ";
}
}
echo "\n";
}
}
Use print(' '), if you want to go to next line put print(' ')."\n"
JavaScript:
Solution:
function StairCase(n){
let x = [];
for(let i = 0; i<n; i++){
while(x.length < n){
x.push(" ");
}
x.shift();
x.push("#");
console.log(x.join(''));
} } //StairCase(6)

Convert simple string to Required Format : PHP

I would like to Convert simple string to set based on below logic
if string is 3,4-8-7,5 then I need the set as (3,8,7),(4,8,5).
The Logic behind to building the set are we need to consider ',' as OR condition and '-' as AND condition.
I am trying my best using For loop :
$intermediate = array();
$arry_A = explode('-', '3,4-8-7,5');
for ($i = 0; $i < count($arry_A); $i++) {
$arry_B = explode(',', $arry_A[$i]);
for ($j = 0; $j < count($arry_B); $j++) {
if (count($intermediate) > 0) {
for ($k = 0; $k < count($intermediate); $k++) {
$intermediate[$k] = $intermediate[$k] . ',' . $arry_B[$j];
}
} elseif (count($intermediate) === 0) {
$intermediate[0] = $arry_B[$j];
}
}
}
echo $intermediate, should give final result.
This Code works correctly, Try this
<?php
$intermediate = array();
$str="";
$val='3,4-8-7,5';
$vals=str_replace(',','-',$val);
$j=1;
$arry_A = explode('-',$vals );
$str.='(';
for ($i = 0; $i < count($arry_A); $i++) {
if($j==3){
$str.=$arry_A[$i].',';
$str.='),';
$str.='(';
$j=1;
}
else
$str.=$arry_A[$i].',';
$j++;
}
echo substr($str, 0, -2);
?>

what's wrong with my php codes?

I wanted to convert my Javascript code for creating a triangle to PHP codes, the Javascript codes works but the PHP code doesn't. This is what I have in my PHP codes, I tried to run it but ended up with a fatal error and undefined variable. I understand javascript but not php...
<?php
{
$size = $_POST['size'];
$firstChoice = $_POST['firstChoice'];
$secondChoice = $_POST['secondChoice'];
echo "<textarea>";
$allLines = '';
for ( $i = 1; $i <= $size; $i++ )
{
$oneLine = createLine ( $i, $i % 2 ? $FirstChoice : $secondChoice );
$allLines += $oneLine + "\n";
}
echo "$allLines";
function createLine ($size, $symbol) {
$aLine = '';
for ( $j = 1; $j <= $size; $j++ )
{
echo $aLine += $symbol;
}
echo "$aLine";
echo "</textarea>";
}
?>
It should look like this if size = 5, firstChoice = # and secondChoice = &
#
&&
###
&&&&
#####
What is $createLine ? Looks as if you're trying to use it as a function, but it is not defined anywhere.
Edit:
You need to declare the function in php
function createLine($size, $symbol) {
// code
}
And when you call it, just call it by the name, don't add a $.
$line = createLine($a, $b);
See documentation on php User-defined functions.
Working:
There were a few issues including: string concatenation should be using the . operator not +, a typo in $FirstChoice, and the function needs to be defined before you use it.
<?php
$size = $_POST['size'];
$firstChoice = $_POST['firstChoice'];
$secondChoice = $_POST['secondChoice'];
function createLine($size, $symbol) {
$aLine = '';
for ($j = 1; $j <= $size; $j++) {
$aLine .= $symbol;
}
return $aLine;
}
echo "<textarea>";
$allLines = '';
for ($i = 1; $i <= $size; $i++) {
$oneLine = createLine($i, $i % 2 ? $firstChoice : $secondChoice);
$allLines .= $oneLine . "\n";
}
echo "$allLines";
echo "</textarea>";
?>
Use createLine(...) and not $createLine(...)
I suppose you have javascript function like below
<script>
function createLine (...)
{
...
}
</script>

Categories