Custom Break Command/Function with create_function() in PHP - php

I'm wondering if it is possible in PHP to create a custom break command/function.
For example,
<?php
$custombreak = create_function('$a', 'if ($a == 3) break 1;');
$i = 0;
do {
echo $i . '<br />';
$i++;
$custombreak($i); //<-- I'd like to break the loop with a custom function.
// if ($i==3) //<-- this is not what I'm looking for
// break;
} while ($i < 10);
?>
This is not valid PHP code but I hope you get what I'm trying to say. I'd like to escape the loop with the function.

Even if you create normal function
function foo() {
break 2; // this is not valid
}
while(true) {
foo();
}
that doesn't work. This is what programmers do:
function foo() {
return true;
}
while(true) {
if(foo()) break;
}
So your code would be..
http://codepad.org/lztnGflZ

<?php
function control($a){
if($a==3)
return false;
return true;
}
$i = 0;
do {
echo $i . '<br />';
$i++;
} while ( ($i < 10) && (control($i)) );
?>
is it an answer for this question ?

I found a way with Exceptions.
$i = 0;
try {
do {
$i++;
echo $i . '<br />';
custombreak($i);
} while ($i <= 10);
} catch (Exception $e) {}
function custombreak($i) {
if ($i > 3) throw new Exception("");
}
Thanks all.

you can use this control in while loop. Don't need to write a function i think.
<?php
$i = 0;
do {
echo $i . '<br />';
$i++;
} while ( ($i < 10) && ($i!=3) );
?>
You know multiple controls don't you ?

Related

How to externalize function for parallel processing in PHP

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

Function With/Without Passing an argument - PHP

Below is a function I created for inserting break lines.
It works fine like this; br(2); //any number, 2 as an example.
However I would like it to work if I typed just br(); it will use 1, but if I specify a number it will use that. Sort of as a default value if none is specified, I've looked throughout google, but can't find the right words to search and find te answer I suppose.
function br($i) {
$j = 0;
while ($j <= $i) {
echo '<br />';
$j++;
}
}
You want Default Parameters. Maybe just:
function br($i=1) {
echo str_repeat('<br />', $i);
}
You want to use a default value:
function br($i = 1) {
$j = 0;
while ($j <= $i) {
echo '<br />';
$j++;
}
}
Reference: PHP Manual - Function arguments
Add 1 as the default
function br($i = 1) {
$j = 0;
while ($j <= $i) {
echo '<br />';
$j++;
}
}
You can try this:
function br($count = 1)
{
while($count) {
echo '<br />';
$count--;
}
}
The "$count = 1" part designates $count as an optional parameter.
http://php.net/manual/en/functions.arguments.php#functions.arguments.default

Sum of Prime numbers

I have the following code, to output all prime numbers from array. I would like to get the sum of the output in ex: 2+3+5 = 10, Any hint how to get that ?
$n = array(1,2,3,4,5,6);
function prime($n){
for($i=0;$i<= count($n);$i++){
$counter = 0;
for($j=1;$j<=$i;$j++){
if($i % $j==0){
$counter++;
}
}
if($counter == 2){
print $i."<br/>";
}
}
}
print prime($n);
Then this should work for you:
(Here i used $sum which i initialized before the foreach loop and then used the += operator to add the sum together)
<?php
$n = array(1,2,3,4,5,6);
function prime($n){
$sum = 0;
foreach($n as $k => $v) {
$counter = 0;
for($j = 1; $j <= $v; $j++) {
if($v % $j == 0)
$counter++;
}
if($counter == 2) {
echo $v."<br/>";
$sum += $v;
}
}
echo "Sum: " . $sum;
}
prime($n);
?>
Output:
2
3
5
Sum: 10
As #IMSoP commented above, one option is to compile the list of primes into a new array:
$m = [];
// looping code...
// If prime:
array_push( $m, $primeNumber );
Then, when you're done, you can do your printing mechanism:
print implode( "<br />", $m );
And then you can do your summing mechanism:
print "<p>Sum: " . array_sum( $m ) . "</p>";
The added benefit here is you can split out each piece of functionality into it's own function or method (which you should do to have a good design).
try this
<?php
define('N', 200);
function isPrime($num)
{
if ($num == 2 || $num == 3) { return 1; }
if (!($num%2) || $num<1) { return 0; }
for ($n = 3; $n <= $num/2; $n += 2) {
if (!($num%$n)) {
return 0;
}
}
return 1;
}
for ($i = 2; $i <= N; $i++) {
if (isPrime($i)) {
$sum += $i;
}
}
echo $sum;
You can try something like this:
function isPrime($n){
if($n == 1) return false;
if($n == 2) return true;
for($x = 2; $x <= sqrt($n); $x++){
if($n % $x == 0) return false;
}
return true;
}
$sum = 0;
$n = array(1,2,3,4,5,6);
foreach($n as $val){
if(isPrime($val)) {
echo $val . "<br />";
$sum += $val;
}
}
echo "Sum: " . $sum;
<?php
$num = 100;
for($j=2;$j<$num;$j++)
{
for($k=2;$k<$j;$k++)
{
if($j%$k==0)
{
break;
}
}
if($k==$j)
{
$prime_no[]=$j;
}
}
echo "<pre>";
print_r($prime_no);
echo "</pre>";
for($j=0;$j<count($prime_no);$j++)
{
$myprimeAdd = $prime_no[$j] + $prime_no[$j+1];
if(in_array($myprimeAdd,$prime_no))
{
echo "Resultant Prime No:-", $myprimeAdd;
echo nl2br("\n");
break;
}
}
?>

For loops for array in PHP

How would I group 5 numbers in an array into each line? I've tried this code below but it results in something I'm not expecting it to be.
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
for ($i=0; $i<5; $i++)
{
echo ($result_data[$i]);
}
echo ("\n");
}
Result:
239298246244268
239298246244268
239298246244268
239298246244268
This loop keep repeating the first 5 numbers in my array. How do I make it to loop for every 5 numbers instead in my whole array of numbers? Thank you!
$x should be your index for the echo. Try this instead:
<?php
$result_data = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
for ($x = 0; $x < count($result_data); $x++)
{
echo ($result_data[$x]);
if(($x+1)%5==0)
{
echo ("\n");
}
}
use this $result_data[$x]
try this
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
if($x%5==0)
{
echo ("\n");
}
echo ($result_data[$x]);
}
Don't know much about your $result_data Array, but probably it should go like this:
$arrayCount = count($result_data);
for ($x = 0; $x < $arrayCount; $x++)
{
for ($i=0; $i<5; $i++)
{
echo ($result_data[$x][$i]);
}
echo ("\n");
}
I think you want to do something like this
$i = 0;
foreach($result_data as $result) {
echo $result;
if($i < 5) {
echo ",";
} else {
echo "<br/>\n";
$i = 0;
}
$i++;
}
Something like this?
$chunks = array_chunk($result_data, 5);
foreach($chunks as $chunk) {
echo implode('', $chunk);
echo "\n";
}
See http://uk3.php.net/manual/en/function.array-chunk.php
Try this several line code:
$valuesDelimiter = ', ';
$lineDelimiter = "\n";
$input_array = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
$slited_array = array_chunk($input_array, 5);
array_walk($slited_array, function(&$arr) {$arr = implode($valuesDelimiter, $arr);});
$result = implode($lineDelimiter, $slited_array);

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