This question already has answers here:
Adding 2 to a variable each time
(5 answers)
Closed 1 year ago.
So I'm trying to make it so the computer counts up to ten by two and making a new line each time. When I tested this my entire computer crashed. What's wrong with it?
<?php
$test = 0;
while ($test < 10) {
$test + 2;
echo $test . "/n";
}
?>
Change:
$test + 2;
to:
$test += 2;
Currently, $test is always 0 in your code, since you are not assigning a new value to it, hence the infinite loop.
Additionally, you would also want to change:
echo $test . "/n";
to:
echo $test . "\n";
Since you need to use a backslash to indicate a new line character.
N.B. In PHP you can also use the PHP_EOL constant to indicate the end of a line.
Here you just sum $test with 2 but did not assign it back to $test
$test + 2;
Trying replace it by $test += 2;
Another point is /n is not "making a new line" as you expected, change it to \n instead.
Although you can use while statement, this is a good case to use for instead.
for($i=0; $i < 10; $i += 2)
{
echo $i . PHP_EOL;
}
Usually while is used to evaluate something every loop, some variable that can change inside the while, like a bool variable or an "infinite" loop until break.
When you have a already defined number of loops, for is usually a better approach.
Related
Need to hep to change multiple characters in a string using some loop without built-in functions in PHP.
<?php
$givenString = "School";
$i=0;
while($givenString[$i]){
$i++;
if($givenString[$i] == o){
$givenString[$i] = 0;
}
}
echo $givenString;
?>
Result: Sch0ol
Required Result: Sch00l
Because your loop logic is out of order. Feed in the string "ooooo" and you'll get "o0ooo" out. It skips the first letter because the first thing you do is move the index ahead, and it stops after the first replacement because you're testing the character that you just replaced, and "0" type-juggles to boolean as false.
Move $i++ to the end of the loop and you'll get "00000", but also Warning: Uninitialized string offset 6. This is because you're relying on the error to break the loop. You need to bound the loop on the length of the string, not the content.
So:
$givenString = "oooooo";
$i=0;
$c=strlen($givenString);
while($i<$c){
if($givenString[$i] == 'o'){
$givenString[$i] = 0;
}
$i++;
}
echo $givenString;
or we can condense that with for loop:
$givenString = "oooooo";
for( $i=0, $c=strlen($givenString); $i<$c; $i++ ){
if($givenString[$i] == 'o'){
$givenString[$i] = 0;
}
}
echo $givenString;
For completeness, the un-quoted o in your post only works because pre-8.0 PHP assumed that unquoted constants were just "oopsies" meant to be strings and replaced them with their string equivalent, issuing a Notice like Notice: Use of undefined constant o - assumed 'o', which can potentially have serious side-effects.
This error also indicates that you're using a version of PHP that is no longer supported, and you should ensure that you are writing code on a supported version.
In your current code, you are replacing all o to 0 which is off-track with respect to replacing oo to 00 and also skipping the current o at hand doesn't make sense. Also, as already pointed out, matching a string with a string is better than comparing with just o directly.
You can instead match o with o and check if string contained a previous o or not. If it did, mark both previous and current location as 0, or else, leave it as is. Since you didn't wish to use inbuilt functions, you can use null-coalescing operator(??) to check with the length of the string as well.
<?php
function modify($string){
for($i = 1; ($string[$i] ?? false) !== false; ++$i){
if($string[ $i ] === 'o' && $string[$i - 1] === 'o'){
$string[ $i ] = $string[$i - 1] = '0';
}
}
return $string;
}
Online Demo
This question already has answers here:
What is the most efficient way to count all the occurrences of a specific character in a PHP string?
(4 answers)
Closed 5 years ago.
I am trying to separate 2 symbols from a string and then
count how many of these symbols there are.
So if i had : 1110001110000
Then it should find that there are 6= 1's and 7= 0's
So This is what I have tried:
Essentially what I need, is to read the string indexes in code would be string[$i] then IF there is a 1 or a 0 count it.
I tried using a for-loop
for ($i=0; $i < $getInput[$i] ; $i++) {
if ($getInput[$i] == 1) {
echo "ONE";
} elseif ($getInput[$i] == 0) {
echo "ZERO";
}
}
Here im trying to echo out ONE for everytime ther is a 1 and ZERO for everytime theres a zero.
$counter = 0;
foreach ($getInput as $key) {
echo $key;
}
here i tried to utilize a foreach, here I am not really declaring to see for One index, i tried putting a for each in a for but needless to say, it didn't work.
Using substr_count, you can do this in a fairly straightforward way:
echo substr_count("1110001110000", '1'); //Echos 6
echo substr_count("1110001110000", '0'); //Echos 7
Substr_count.
http://php.net/manual/en/function.substr-count.php
$str = "1110001110000";
Echo "there is " .substr_count($str, "0") ." zeros \n";
Echo "there is " .substr_count($str, "1") ." ones \n";
https://3v4l.org/BQEiR
If you want to output it as your code implies (one one one zero) you can use numberformatter.
Here I split the string to an array and loop through it and output the spellout of each number.
$str = "1110001110000";
$arr = str_split($str);
$nf = new NumberFormatter("en", NumberFormatter::SPELLOUT);
Foreach($arr as $numb){
echo $nf->format($numb) . " ";
}
Output:
one one one zero zero zero one one one zero zero zero zero
https://3v4l.org/nHX59
This question already has answers here:
Shunting Yard implementation in PHP needed, interpret and parse a string perform a mathematical comparison and return a boolean result
(4 answers)
Closed 7 years ago.
Why this 2 code not echo same result ?
On first code echo *57, But i want to echo 35 like on second code.
How can i do that ?
<?PHP
$fomular = "*5";
$x = "7";
$res = $fomular."".$x;
echo $res;
?>
<?PHP
echo 5*7;
?>
There are a couple of issues.
In your example
...
$res = $fomular."".$x;
...
Is the same as saying
...
$res = "*5".""."3";
...
So that explains the "*53" been echoed/
...
$res = $fomular + $x;
// or
$res = $x + $fomular;
...
Will return 12 as it will not evaluate the "*" but rather add the numbers.
You could use eval( ... ) but it is evil and would really advise against it.
...
echo eval( "5*" . "7" . ";");
...
So your best bet, if you really want to echo the result, would be to write your own function to parse the 2 strings and do the operation.
That is because when you use .(dot) operator it appends the two variables.
You have to use code like below to get the desired output
$formular = 5;
$x=7;
$res=$formular * $x;
echo $res;
$formular = 5;
$x = 7;
$res = $formular * $x;
echo $res;
. (dot) in php is a string concatenating operator! if you try to use it with any type of variables, it converts they to string and put together. Sample: $x = 5 . 7 -> $x = '57'; but, if you use any kind of mathematicals operators (*, /, +, -), php will convert both operands to numeric form (float or int), then execute your formula and give a result $x = 5 * 7; -> $x = 35;
In short: use only mathematicals operators for executing formulas, not a dot. (sory for my bad english)
See the following code snippet
$i=1;
echo $i.($i++);
in a quick, I thought the result would be 12 but the actual result is 21.
also
echo $i,$i++;
I thought it would be 12 but its 11 .
echo ($i = ($i++)); //result is 1
echo ($i = ($i+1)); //result is 2
But why?
When a variable is not involved into any arithmetic operation (like your first $i), PHP will not create a temporary variable.
Thus, your first $i will be evaluated at the end of the statement, when $i++ has already been executed.
To prevent this, you can still write:
echo ($i += 0).($i++);
But this is obviously not a good coding practice.
EDIT: When you use , it is actually syntactic sugar to shorten two PHP statements. It is strictly equivalent to:
echo $i;
echo $i++;
Since incrementation is executed after the last statement, 11 is indeed the result.
First example
Code in brackets is evaluated first - in this case ($i++). The value of $i is taken (1) and then the variable is incremented to 2. So you then have this, where $i is 2.
echo $i . '1'
From this, the value of $i is substituted in, and you get '2' . '1', which is concatenated to give '21'.
Second example
It's easier to rewrite this to clear up the , separator. The line echo $i, $i++; is equivalent to:
echo $i;
echo $i++;
The first line obviously outputs 1, and the second will output that same value, then increment $i (++ is the post-increment operator). If you were to put another echo $i; at the end, it would output 2.
As per the PHP documentation stated at: Operator Precedence
First Case
$i=1;
echo $i.($i++);
$i is initialized to value 1. Now, ++ follows a higer precedence than . and it has right-associative. This means your $i++ will be evaluated first. In this case , the value of $i++ will be 1 and the next value of $i will get incremented to 2. hence $i is 2
Now . has the next precendence after ++, which is left-associative. hence it will evaluate values starting from left.
so $i=2 and $i++ =1, hence the output 21
Second Case
$i=1;
echo $i,$i++;
Here, there is only one operator ++. Hence the need for comparision of precedence doesn't arise. Hence, it will be evalauted by default standard of left-associative. $i = 1, $i++ = 1. Hence 11
Third Case
echo ($i = ($i++)); //result is 1
In this case, now = is an assignment operator and is right-associative, so $i++ = 1. And since it is an assignment operator value of $i++ will be stored in $i. hence echo ($i = 1); which will result in output being 1.
Fourth Case
echo ($i = ($i+1)); //result is 2
Again, this will be right-associative, so $i+1 = 2. hence echo ($i = 2); which will result in output being 2.
Firstly for the second place it uses $i eq 1
Then it increases it to 2;
So for the first place it uses 2 and for the second - 1
I am trying to create a script that takes a $$variable and adds them to each other a number of times (based on another variable) - $total
This script is part of a much larger script that contains a few SQL queries and loops, hence the $$value as opposed to the usual $value
My current (static) script is like so:
$$value = ($$value + $$value + $$value + $$value + $$value);
This will work if I continue to modify the number of + $$value within the brackets but I need it to auto calculate and ammend itself so that it always writes the correct number of + $$value
I have tried using str_repeat() but it only fetches the first value of the $$value variable and then repeats that value (not grabbing the next value and so on). I have also tried creating a loop, which also didn't work.
I need something that will look at $total and from that number produce something similar to the following:
$$value = ($$value * $total)
The above will multiply the numeric value of the $$value and therefore not return the result I want.
Can anyone help?
Many thanks,
Tom
Pastebin Link to my script: http://pastebin.com/7Qg02hWB (in the pastebin, $$value is $$ob_id and $total is $o_total)
Not 100% sure what you mean, but how's
$foo = "";
for ($i = 0; $i < $total; $i++) $foo .= $$value;
$$value = $foo;
This will loop over $total times and concatenate it. If you're having problems like it's adding it as an integer for some reason you could always do a cast like (string) $$value. I know you said you tried a loop but we have no code so it could have been a problem with your code.
this?
perhaps you need powers?
$total = 5;
$$variable = 2; // random value; and why i have two 2 $$ ?
for($x=0;$x<$total;$x++) {
$$variable += $$variable;
}
echo $$variable;
OR,
$total = 5;
$$variable = 2;
echo "<br>POWER of 2^$total: ".pow($$variable,$total);