I am writting my own calculator on PHP.
I have a problem with my code because i don't know where i am trying to read too far in the string. So if anyone can enlighten me ..
The exact error i get is :
PHP Notice: Uninitialized string offset: 4 in /home/salim/Bureau/web/piscine_php/d01/ex11/do_op_2.php on line 76
Here is the code below :
function decoupe ($argv)
{
global $nbr1;
global $nbr2;
global $sign;
$string = NULL;
$string = trim($argv[1], " \t");
echo $string;
echo "\n";
$x = 0;
while($string[$x])
{
if (is_numeric($string[0]) == false)
error_msg();
if (is_numeric($string[$x]) && $string[$x + 1])
{
while (is_numeric($string[$x]))
{
$nbr1 .= $string[$x];
$x++;
}
}
if (is_thisoperator(substr($string, $x)))
{
$sign .= $string[$x];
$x++;
}
else
{
error_msg();
}
if ($string[$x + 1] && is_numeric($string[$x]))
{
while (is_numeric($string[$x]))
{
$nbr2 .= $string[$x];
$x++;
}
}
else
{
error_msg();
}
}
Don't use $string[$x] as a way to test whether $x is a valid index in the string. It prints a warning when $x is outside the string. Use $x < strlen($string) instead. So change:
while ($string[$x])
to
while ($x < strlen($string))
and change
if ($string[$x + 1] && is_numeric($string[$x]))
to
if ($x + 1 < strlen($string) && is_numeric($string[$x]))
Related
function fctdeux(string $str)
{
$nbr;
$nbr = 0;
while($str >= '0' && $str <= '9')
{
$nbr = $nbr * 10 + ($str - '0');
$str++;
}
return $nbr;
}
function testeur(string $expr)
{
$nbr;
$nbr2;
$op;
$nbr = anal_number($expr);
while($expr)
{
while($expr == ' ')
{
$expr++ ;
$op = $expr;
if($op != '/' && $op != '*' && $op != '%')
return $nbr;
}
$expr++;
$nbr2 = anal_number($expr);
if($op = '/')
{
$nbr /= $nbr2;
}else
if($op == '*')
{
$nbr *= $nbr2;
}else
{
$nbr %= $nbr2;
}
}
return $nbr;
}
echo eval_expr(2+3);
Hello I try to create a calculator for when call the function in end of code echo exemple(2+3)and in terminal call the file php exemple.php its writing result of calcul(5). I have this error :
PHP Warning: Division by zero in /home/username/project/project.php on line 125
its where I have
$nbr /= $nbr2;
in code
Division by 0 is impossible. How many nothings go into X? The answer is a mathematical melt down. However, you can catch it in your code:
if ($nbr2 == 0) {
# code to either return an error message about using 0 to divide
# or you could return NaN (not a number) as the value.
}
I have to convert hexadecimal to decimal with PHP (without using hexdec) for my homework, but my code does not convert properly.
For example, when I use the function HexToDez ("1F4");, the answer should be 500, not 1.
Why is it not working?
the code
<?php
function Replace ($i)
{
switch (strToLower ($i))
{
case "a" : return 10;
case "b" : return 11;
case "c" : return 12;
case "d" : return 13;
case "e" : return 14;
case "f" : return 15;
default : return $i;
}
}
function HexToDez($i) # 1F4
{
$input=$i;
$num=strlen ($input) ;
$pos=0;
$output="";
$hochzahl="";
while($pos<$num)
{
$mid = substr ($input, $pos, 1);
$pos++;
return $end=Replace ($mid);
}
while ($end != 0){
$zahl = $input%10;
$output += $zahl*pow(16, $hochzahl);
$end = $end/10;
$hochzahl++;
}
echo $output;
}
?>
here is "classic" algorithm for you to consider, check the comments:
function HexToDez($s) {
$output = 0;
for ($i=0; $i<strlen($s); $i++) {
$c = $s[$i]; // you don't need substr to get 1 symbol from string
if ( ($c >= '0') && ($c <= '9') )
$output = $output*16 + ord($c) - ord('0'); // two things: 1. multiple by 16 2. convert digit character to integer
elseif ( ($c >= 'A') && ($c <= 'F') ) // care about upper case
$output = $output*16 + ord($s[$i]) - ord('A') + 10; // note that we're adding 10
elseif ( ($c >= 'a') && ($c <= 'f') ) // care about lower case
$output = $output*16 + ord($c) - ord('a') + 10;
}
return $output;
}
echo HexToDez("1F4"); // outputs 500
also, you can use intval function to do the same, just convert your number into hex representation, like 0x###
function HexToDez($s) {
return intval('0x'.$s, 16);
}
What's wrong with this code. I want to read the number of blank spaces without using any built in function, but it wont return or read the blank spaces:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while ($string[$i] != '' & $string[$i + 1] != '') {
if ($string[$i] == "" || empty($string[$i])) {
die("cdsd");
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
It's always going into the else part and never goes into the if statement. I even tried using isset() but that also didn't work. Where am I making a mistake?
Just loop while the string offset isset() and check if it equals a space. No need to do anything with $i+1:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while (isset($string[$i])) {
if ($string[$i] == " ") {
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
This outputs:
canyoulookintothis??4
Once you've got your code right, you will always run into an string index error and you will need the isset() built in function to check before performing operations.
In other words, the i for the index will eventually point beyond the last letter of the string, this will cause a PHP error. You can use isset() to check for it and break out of the loop. Example:
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while (isset($string[$i])) {
if ($string[$i] == " ") {
$breakPoints++;
} else {
if($string[$i] != ''){
print_r($string[$i]);
}
}
$i++;
}
echo("<br />Number of spaces: ".$breakPoints
spaces is not empty, it will tack size.
so use this
$string = "can you look into this??";
$i = 0;
$breakPoints = 0;
while ($string[$i] != '' & $string[$i + 1] != '') {
if ($string[$i] == " ") {
echo " ";
$breakposition = $string[$i];
$breakPoints++;
} else {
print_r($string[$i]);
}
$i++;
}
echo($breakPoints);
DEMO
or try this code,
use preg_match_all.
$matches = " ";
$numSpaces = preg_match_all('/[ ]/', $string , $matches);
or Use this::
substr_count($string , ' ');
I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..
I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.
Here the code:-
<?php
function numberOfR($string1)
{
for($i=0;$i <strlen($string1);$i++)
{
if($string1[$i]!='K')
{
$count++;
}
}
return $count;
}
$return_value= numberOfR("RKKRK");
echo "R's count is:";
echo $return_value;
?>
<?php
function getLongetSegment($string) {
$currentSegmentChar='';
$currentSegment="";
$biggestSegment="";
$current_length=0;
$biggest_length=0;
for($i=0;$i<strlen($string);$i++) {
$char = $string[$i];
if($char != $currentSegmentChar || $currentSegmentChar == '') {
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
$biggest_length = $current_length;
}
$currentSegmentChar = $char;
$currentSegment = $char;
$current_length = 1;
}
elseif($currentSegmentChar != '') {
$currentSegment .= $char;
$current_length++;
}
}
if($current_length >= $biggest_length) {
$biggestSegment = $currentSegment;
}
return array("string" => $biggestSegment,"length" => $biggest_length);
}
print_r(getLongetSegment("RKKRGGG"));
?>
Result: GGG
You can use preg_match_all over here as
preg_match_all('/(.)\1+/i','RKKRRRRK',$res);
usort($res[0],function($a,$b){
return strlen($b) - strlen($a);
});
echo $res[0][0];
Not sure if I understood this quite right. Something like this:
function maxCharSequece($string1)
{
$maxSeq = $seq = 0;
$maxChar = $lastChar = null;
for( $i = 0; $i < strlen($string1); $i++ )
{
$c = $string1[$i];
if (!$lastChar) $lastChar = $c;
if ( $lastChar == $c ){
if ( ++$seq > $maxSeq ) $maxChar = $lastChar;
}
else {
$maxSeq = $seq;
$seq = 0;
}
}
return $maxChar;
}
You can use preg_replace_callback to receive all continuous segments and select the longest
$sq = '';
preg_replace_callback('/(.)\1+/',
function ($i) use (&$sq) {
if(strlen($i[0]) > strlen($sq)) $sq = $i[0];
}, $str);
echo $sq . " " . strlen($sq);
so I am new at the idea of recursion and i wrote this simple code to factor a number ($n) this is the code:
$n = 120;
$y = 1;
function factor($n, $y) {
if($y > $n) {
return 1;
} else {
$x = $n / $y;
list($whole, $dec) = array_pad(explode('.', $x), 2, Null);
if($dec == '') {
echo 'x:' . $x . ' y:' . $y . '</br>';
return factor($n, ($y + 1));
}
}
}
this is what the code outputs:
x:120 y:1
x:60 y:2
x:40 y:3
x:30 y:4
x:24 y:5
x:20 y:6
so my question is why does this stop before it completes?
Your next step would be 120 / 7 which equals 17.142857....
So this check fails and as such the recursion does not happen:
if($dec=='') // $dec would equal to 142857.....
{
echo'x:'.$x.' y:'.$y.'</br>';
return factor($n,($y+1));
}
else
{
$x=$n/$y;
list($whole,$dec)=array_pad(explode('.', number_format($x)), 2, Null);
if($dec=='')
{
echo'x:'.$x.' y:'.$y.'</br>';
return factor($n,($y+1));
}
}
PART OF DECIMAL LIMITATION
There are two things I see wrong with your example:
Your recursion stops the first time it encounters a fractional value. The tail recursion (return factor($n, $y + 1);) only occurs when $dec == ''. Otherwise, the function simply exits. That's why it stops when $y is 7.
Your condition for ending recursion ($y > $n) is incorrect. You want to break the recursion when the divisor is greater than the quotient — i.e., when $y > $x — because that means you've found all the integer factors.
I think this is what you want:
$n = 120;
$y = 1;
function factor($n, $y) {
$x = $n / $y;
if($y > $x) {
return 1;
} else {
list($whole, $dec) = array_pad(explode('.', $x), 2, Null);
if($dec == '') {
echo 'x:' . $x . ' y:' . $y . "</br>\n";
}
return factor($n, ($y + 1));
}
}
echo factor($n, $y);