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>
Related
I am going to play with parallel processing in PHP. https://www.php.net/manual/en/book.parallel.php
I could make something very basic to understand the main concept.
Here is where I am :
<?php
for ($i = 0; $i < 7; $i++) {
$runtime = new \parallel\Runtime();
$runtimes[] = $runtime;
echo "starting thread $i from main thread" . PHP_EOL;
$future = $runtime->run(function($i){
$nbtot = 0;
echo "I am thread $i " . PHP_EOL;
for ($j = 0; $j < 5; $j++) {
echo "thread $i in loop $j " . PHP_EOL;
$nbsec = rand(0, 10);
$nbtot = $nbtot + $nbsec;
sleep($nbsec);
}
return array($i, $nbtot); //returning an array to the main thread
}, array($i)); //passing argument to the closure
$futures[] = $future;
}
$ct = count($futures);
while ( $ct > 0 ) {
echo "$ct active threads" . PHP_EOL;
foreach ($futures as $key => $future) {
if ($future->done()) {
print_r($future->value());
unset($futures[$key]);
}
}
sleep(2);
$ct = count($futures);
}
?>
For maintenance purpose, I would like to put the code of the function (closure) in another file. I guess that \parallel\bootstrap is made for it, but I can't figure out how to make it work. What should I change my current code ? and what should I place in the other file ?
After some hard time and the support of Joe Watkins, here is the answer I was looking for :
<?php
\parallel\bootstrap('test_threads_inc.php');
for ($i = 0; $i < 7; $i++) {
echo "starting thread $i from main thread" . PHP_EOL;
$futures[] = \parallel\run(function($a) {return myfunction($a);}, array($i)); //passing argument to the closure
}
$ct = count($futures);
while ( $ct > 0 ) {
echo "$ct active threads" . PHP_EOL;
foreach ($futures as $key => $future) {
if ($future->done()) {
print_r($future->value());
unset($futures[$key]);
}
}
sleep(2);
$ct = count($futures);
}
?>
and test_threads_inc.php :
<?php
function myfunction($i) {
$nbtot = 0;
echo "I am thread $i " . PHP_EOL;
for ($j = 0; $j < 5; $j++) {
echo "thread $i in loop $j " . PHP_EOL;
$nbsec = rand(0, 10);
$nbtot = $nbtot + $nbsec;
sleep($nbsec);
}
return array($i, $nbtot); //returning an array to the main thread
}
?>
I wrote this include file test_inc.php :
<?php
$myworker = function($i){
...
return array($i, $nbtot); //returning an array to the main thread
}
?>
and then include it at the beginning of main script : include('test_inc.php');. I could replace the function description by the variable just like this :
$future = $runtime->run($myworker, array($i));
It's possible to work with class inside the Closure function. For that, you need to use require_once inside the function to include them. It's probably possible to include the require_once outside the Closure function if you use a bootstrap
<?php
echo my_string_replace("world","jonathan","hello world helloworld");
function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>
I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"
error_reporting(0); used for hide "Uninitialized string offset" notice.
<?php
function str_v2($num){
error_reporting(0);
for($i=0; $num[$i] != "";$i++);
echo $i; }//end of function
$name = "Hope this will work.";
echo str_v2($name);
?>
That was a fun brain teaser. Here you go:
echo my_string_replace("world", "jonathan", "hello world helloworld");
function my_string_replace($find, $replace, $string)
{
$characterCount = strlen($string);
$findCount = strlen($find);
$replaceCount = strlen($replace);
for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
if ($string[$i] == $find[0]) {
$j = 1;
$found = true;
while ($j < $findCount) {
if ($string[$i + $j] != $find[$j]) {
$found = false;
break;
}
$j++;
}
if ($found) {
// copy string until current position
$replaced = '';
for ($x = 0; $x < $i; $x++) {
$replaced .= $string[$x];
}
// append replacement
$replaced .= $replace;
// copy after match till end
for ($x = $i + $findCount; $x < $characterCount; $x++) {
$replaced .= $string[$x];
}
// continue with replaced string, after replacement
$string = $replaced;
$characterCount = strlen($string);
$i = $i + $replaceCount;
}
}
}
return $string;
}
Below is my Code to Reverse a String..
The code runs well but I need to wrap this code inside Paramaterized function
in which user pass a string inside function and get return output.
<?php
$string = trim("This");
$len =strlen($string);
$stringExp = str_split($string);
for ($i = $len-1; $i >=0;$i--)
{
echo $stringExp[$i];
}
?>
for Ex -
I want above string reversal code logic like below function...
<?php
$str = "rahul";
echo reverse($str);
function reverse($str)
{
for ($i = 0, $j = strlen($str) - 1; $i < $j; $i++, $j--) {
$tmp = $str[$i];
$str[$i] = $str[$j];
$str[$j] = $tmp;
}
return $str;
}
?>
Simply try this
$str = "rahul";
echo reverse($str);
function reverse($str)
{
$tmp = '';
for($i = (strlen($str)-1);$i >= 0; $i--) {
$tmp .= $str[$i];
}
return $tmp;
}
There is strev() function which does it but if you need write your own here is the code
$str = "abcde";
function reverse ($str)
{
$output = '';
for ($i = strlen($str)-1; $i >= 0 ; --$i) {
$output .= $str[$i];
}
return $output;
}
echo reverse($str);
I'm try to print an array where every other value is reassigned, as examples (from this):
17.34502870451717,62.46137370987033
To this:
62.46137370987033,17.34502870451717
That part have I succeeded with, but now I have this structure:
[62.46137370987033,[17.34501402936927,]
[62.46123453616544,[17.34525377433593,]
[62.4610178881864,[17.34546663705899,]
This is where I get stuck and do not know how to write.
The structure I want looks like this:
[62.392628, 17.309413],
[62.393162, 17.309193],
[62.393403, 17.30922]
Here is my explode.php (GIST)
<?php
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$wing = "[";
for ($i = 0;$i < count($minion) -1; $i++) {
echo $wing . $minion[$i+1].",";
if($i%2==1) { echo "]<br />"; }
} echo $minion[0] . $wing;
?>
As I understand it, as long as there's always even pairs it should be as easy as;
<?php
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$eol = '';
for ($i = 0;$i < count($minion) -1; $i+=2) {
echo $eol.'['.$minion[$i+1].','.$minion[$i]."]";
$eol=',<br/>';
}
echo '<br/>';
>>> [62.46137370987033,17.34502870451717],
>>> [62.46123453616544,17.34501402936927]
Try This
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$wing = "[";
for ($i = 0;$i < count($minion) -1; $i+=2)
{
echo $kk = $wing . $minion[$i+1].",".$minion[$i]."],<br>";
}
Just a small modification to the given answers
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$str = '';
for ($i = 0;$i < count($minion) -1; $i+=2) {
$str.='['.$minion[$i+1].','.$minion[$i].'],<br/>';
}
echo rtrim($str,','); // to trim ',' at the end
(my first post was not clear and confusing so I've edited the question)
I was studying string manipulation.
You can use strlen() or substr() but cannot rely on other functions that are predefined in libraries.
Given string $string = "This is a pen", remove "is" so that
return value is "Th a pen" (including 3 whitespaces).
Remove 'is' means if a string is "Tsih", we don't remove it. Only "is" is removed.
I've tried (shown below) but returned value is not correct. I've run test test and
I'm still capturing the delimiter.
Thanks in advance!
function remove_delimiter_from_string(&$string, $del) {
for($i=0; $i<strlen($string); $i++) {
for($j=0; $j<strlen($del); $j++) {
if($string[$i] == $del[$j]) {
$string[$i] = $string[$i+$j]; //this grabs delimiter :(
}
}
}
echo $string . "\n";
}
Clarifying, the original quiestion is not Implement a str_replace, It's remove 'is' from 'this is a pen' without any functions and no extra white spaces between words. The easiest way would be $string[2] = $string[3] = $string[5] = $string[6] = '' but that would leave an extra white space between Th and a (Th[ ][ ]a).
There you go, no functions at all
$string = 'This is a pen';
$word = 'is';
$i = $z = 0;
while($string[$i] != null) $i++;
while($word[$z] != null) $z++;
for($x = 0; $x < $i; $x++)
for($y = 0; $y < $z; $y++)
if($string[$x] === $word[$y])
$string[$x] = '';
If you were allowed to use substr() it'd be so much easier. Then you could just loop it and check for the matched value, why can't you use substr() but you can strlen() ?
But without, this works at least:
echo remove_delimiter_from_string("This is a pen","is");
function remove_delimiter_from_string($input, $del) {
$result = "";
for($i=0; $i<strlen($input); $i++) {
$temp = "";
if($i < (strlen($input)-strlen($del))) {
for($j=0; $j<strlen($del); $j++) {
$temp .= $input[$i+$j];
}
}
if($temp == $del) {
$i += strlen($del) - 1;
} else {
$result .= $input[$i];
}
}
return $result;
}
The following code can also used to replace the sub string:
$restring = replace_delimiter_from_string("This is a pen","is", "");
var_dump($restring);
$restring = replace_delimiter_from_string($restring," ", " ");
var_dump($restring);
function replace_delimiter_from_string($input, $old, $new) {
$input_len = strlen($input);
$old_len = strlen($old);
$check_len = $input_len-$old_len;
$result = "";
for($i=0; $i<=$check_len;) {
$sub_str = substr($input, $i, $old_len);
if($sub_str === $old) {
$i += $old_len;
$result .= $new;
}
else {
$result .= $input[$i];
if($i==$check_len) {
$result = $result . substr($input, $i+1);
}
$i++;
}
}
return $result;
}