I was trying to make a program to do synthetic division which requires factoring so I wrote this function to factor an integer which works, but it never changes the values of the php array $factors. Any help will be greatly appreciated.
$factors=array();
$i;
function factor($x){
if($x==0){
echo "(0,0)";
} else {
$n=false;
if($x<0) {
$x=abs($x);
$n=true;
}
for($i=2; $i<=$x; $i++) {
if($x%$i==0){
if($n){
$factors[(count($factors))]=(-1*($x/$i));
$factors[(count($factors))]=($i);
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=(-1*$i);
} else {
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=($i);
}
}
}
}
}
factor(-4);
Try this
function factor($x){
$factors=array();
if($x==0){
echo "(0,0)";
} else {
$n=false;
if($x<0) {
$x=abs($x);
$n=true;
}
for($i=2; $i<=$x; $i++) {
if($x%$i==0){
if($n){
$factors[(count($factors))]=(-1*($x/$i));
$factors[(count($factors))]=($i);
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=(-1*$i);
} else {
$factors[(count($factors))]=($x/$i);
$factors[(count($factors))]=($i);
}
}
} //end for
echo '(' . implode(',', $factors). ')';
} //end if $x == 0
}
factor(-4);
$factors is outside the scope of the function, besides that you were not returning or outputting anything. Seeing as you echo (0,0) I assumed you wanted it echoed such as (2,4,8) etc. Which you can do with implode..
Related
With a program to replace substring in a string without using str_replace
should be generic function should work for below example:
Word : Hello world
Replace word : llo
Replace by : zz
Output should be: Hezz world
Word : Hello world
Replace word : o
Replace by : xx
Output should be: Hellxx wxxrld
This is what i wrote to solve it
function stringreplace($str, $stringtoreplace, $stringreplaceby){
$i=0;$add='';
while($str[$i] != ''){
$add .= $str[$i];
$j=0;$m=$i;$l=$i;$check=0;
if($str[$i] == $stringtoreplace[$j]){
while($stringtoreplace[$j] != ''){
if($str[$m] == $stringtoreplace[$j]){
$check++;
}
$j++;$m++;
}
if($check == strlen($stringtoreplace)){
$n=0;$sub='';
for($n=0;$n<=strlen($stringtoreplace);$n++){
$str[$l] = '';
$sub .= $str[$l];
$l++;
}
$add .= $stringreplaceby;
$i += $check;
}
}
$i++;
}//echo $add;exit;
return $add;
}
I am getting output as helzzworld .
Please take a look what I did wrong or if you have better solution for this please suggest.
You can do this by explode the main string into array then implode your stringreplaceby to your array parts creating new string
<?php
function stringreplce($str,$strreplace,$strreplaceby){
$str_array=explode($strreplace,$str);
$newstr=implode($strreplaceby,$str_array);
return $newstr;
}
echo stringreplce("Hello World","llo","zz")."<br>";
echo stringreplce("Hello World","Hel","zz")."<br>";
echo stringreplce("Hello World"," Wo","zz")."<br>";
echo stringreplce("Hello World","rl","zz")."<br>";
echo stringreplce("Hello World","ld","zz")."<br>";
?>
Try this simplest one, without using str_replace, Here we are using explode and implode and substr_count.
1. substr_count for counting and checking the existence of substring.
2. explode for exploding string into array on the basis of matched substring.
3. implode joining the string with replacement.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
if(substr_count($string, $toReplace))
{
$array=explode($toReplace,$string);
return implode($replacement, $array);
}
}
Solution 2:
Try this code snippet here not best, but working
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
while($indexArray=checkSubStringIndexes($toReplace,$string))
{
$stringArray= getChars($string);
$replaced=false;
$newString="";
foreach($stringArray as $key => $value)
{
if(!$replaced && in_array($key,$indexArray))
{
$newString=$newString.$replacement;
$replaced=true;
}
elseif(!in_array($key,$indexArray))
{
$newString=$newString.$value;
}
}
$string=$newString;
}
return $string;
}
function getLength($string)
{
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$counter++;
}
else
{
break;
}
}
return $counter;
}
function getChars($string)
{
$result=array();
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$result[]=$string[$counter];
$counter++;
}
else
{
break;
}
}
return $result;
}
function checkSubStringIndexes($toReplace,$string)
{
$counter=0;
$indexArray=array();
$newCounter=0;
$length= getLength($string);
$toReplacelength= getLength($toReplace);
$mainCharacters= getChars($string);
$toReplaceCharacters= getChars($toReplace);
for($x=0;$x<$length;$x++)
{
if($mainCharacters[$x]==$toReplaceCharacters[0])
{
for($y=0;$y<$toReplacelength;$y++)
{
if(isset($mainCharacters[$x+$y]) && $mainCharacters[$x+$y]==$toReplaceCharacters[$y])
{
$indexArray[]=$x+$y;
$newCounter++;
}
}
if($newCounter==$toReplacelength)
{
return $indexArray;
}
}
}
}
function ganti_kata($kata,$kata_awal,$kata_ganti){
$i =0; $hasil;
$panjang = strlen($kata);
while ($i < $panjang) {
if ($kata[$i] == $kata_awal) {
$hasil[$i] = $kata_ganti;
echo $hasil[$i];
}
else if ($kata[$i] !== $kata_awal){
$hasil[$i] = $kata[$i];
echo $hasil[$i];
}
$i++;
}
}
echo ganti_kata('Riowaldy Indrawan','a','x');
This code using php
Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}
So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";
I'm working on some PHP code but I'm stuck with a logic.
I need to find out the number of squares from a rectangle.
I'm unable to implement this in PHP.
Please help.
I tried this:
function getcount($length,$breadth,$count=0){
$min=min($length,$breadth);
if($length>$breadth){
$length=$length-$min;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$min;
$count++;
return getcount($length,$breadth,$count);
}
else{
$count+=($length/$min);
}
return $count;
}
But some how it doesn't pass all the use cases.
And i do not know on which use cases, it fails?
I think the easiest way to calculate the number of squares in a rectangle is to substract the found squares from it while it disappears completely.
It works fine for me:
function getcount($width,$height) {
$total=0;
while($width && $height)
{
if($width>$height)
{
$width-=$height;
}
else if($height>$width)
{
$height-=$width;
}
else
{
$width=0;
$height=0;
}
$total+=1;
}
return $total;
}
echo getcount(5,3)."<br/>";
echo getcount(5,5)."<br/>";
echo getcount(11,5)."<br/>";
Output:
4
1
7
In my opinion there is nothing wrong in your code. The output from the code in OP is exactly the same as the output of the code in the accepted answer. You can run this (where getcount() is the function from OP and getcount2() is the function from the Balázs Varga's answer):
for ($i=0; $i<10000; $i++)
{
$a=mt_rand(1,50);
$b=mt_rand(1,50);
$r1 = getcount($a, $b);
$r2 = getcount2($b, $b);
if ($r1 != $r2)
{
echo "D'oh!";
}
}
and it will not return anything at all.
The only flaw is your code will throw a warning message when you run getcount(0, 0).
Also, the second line in your code ($min=min($length,$breadth);) is a bit redundant. You can write the same this way:
function getcount($length,$breadth,$count=0){
if($length>$breadth){
$length=$length-$breadth;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$length;
$count++;
return getcount($length,$breadth,$count);
}
else if ($breadth!=0){
$count++; // there is no need to divide two same numbers, right?
}
return $count;
}
i wanted to arrange this arrays element in assending order and wrote the below code :
<?php
$a=array("z","s","a","j","t","b");
for($i=0;$i<=6;$i++)
{
if ($i[0]<$i[1]) { echo $i[1]; }
else if ($i[1]<$i[2]) { echo $i[2]; }
else if ($i[2]<$i[3]) { echo $i[3]; }
else if ($i[3]<$i[4]) { echo $i[4]; }
else if ($i[4]<$i[5]) { echo $i[5]; }
else if ($i[5]<$i[6]) { echo $i[6]; }
else if ($i[6]<$i[7]) { echo $i[7]; }
else if ($i[7]<$i[8]) { echo $i[8]; }
else if ($i[8]<$i[9]) { echo $i[9]; }
else if ($i[9]<$i[10]) { echo $i[10]; }
else if ($i[10]<$i[11]) { echo $i[11]; }
else ($i[11]<$i[12]) { echo $i[12]; }
}
?>
but i an getting the following error :
Parse error: syntax error, unexpected '{' in C:\wamp\www\arange.php on line 16
how can i rectify it
This snippet is the problem:
else ($i[11]<$i[12]) { echo $i[12]; }
Either edit it into elseif or remove the ($i[11]<$i[12]).
I'd do this differently. Consider using PHP's built in sort() function.
$a = array("z","s","a","j","t","b");
sort($a);
foreach ($a as $element) {
echo "$element\n";
}
Also read about the foreach statement.
$b = '';
$a=array("z","s","a","j","t","b");
foreach($a as $i) if($i > $b) $b = $i;
echo $b;
Check out the manual for a clear example of the elseif/else if syntax. The else part in your code is the problem.
if ($i[5]<$i[6]) { echo $i[6]; }
actually will output something like this;
if ( b < ) { echo ; }
That why you see kinda error...