I want to use a loop to iterate through my array, calling my function to print out all of these messages. I have to somehow keep track of what number person im on. -- im using PHP
<?php
$name_array = array('pon', 'zi', 'pol', 'et');
function name_person($name, $number) {
echo $name . ' is person #' . $number . ' ';
}
for ($i = 0; $i <= 4; $i++) {
$counter = 1;
while ($counter <=4) {
name_person( $name_array[$i], $counter);
$counter++;
}
}
my output should be:
pon is person #1, zi is person #2, pol is person #3, et is person #4
Can you please help me?
you can use array_walk to apply a user supplied function to every member of an array.
Try this code.
$name_array = array('pon', 'zi', 'pol', 'et');
//remove 0 index from array (optional)
$name_array = array_filter(array_merge(array(0), $name_array));
function name_person($name, $number) {
echo $name . ' is person #' . $number . ' ';
}
//apply a user supplied function to every member of an array
array_walk($name_array, 'name_person');
Output:
pon is person #1 zi is person #2 pol is person #3 et is person #4
Try this:
<?php
$name_array = array('pon', 'zi', 'pol', 'et');
function name_person($name, $number) {
echo $name . ' is person #' . $number . ' ';
}
for ($i = 0; $i < 4; $i++) {
name_person( $name_array[$i], $i + 1);
}
for exact output try this:
$name_array = array('pon', 'zi', 'pol', 'et');
function name_person($name, $number) {
echo $name . ' is person #' . $number;
}
foreach($name_array as $k=>$v) {
name_person( $v, $k+1).(($k==sizeof($name_array)-1)?'':', ');
}
There is a nested while loop within for loop.
for loop should run from 0 to <4 instead of <=4.
Lose the $counter variable and just use $i+1 instead.
So it should be:
for ($i = 0; $i < 4; $i++) {
name_person( $name_array[$i], $i+1);
}
Related
When the number 6 is giving I need to calculate till 6: for example: 1+2+3+4+5+6=21. I also need to add the sums of each to an array like: 1+2=3, 1+2+3=6, 1+2+3+4=10, ...
I have tried to make the while loop to be printed and this working fine but nog for array purpose:
<?php
$number = $_POST['number'];
$i = 1;
$cal = 0;
$tussenBerekening = array();
while ($i <= $number) {
echo $i;
$cal = $cal + $i;
array_push($tussenBerekening, $cal);
if ($i != $number) {
echo " + ";
} else {
echo " = " . $cal;
}
$i++;
}
?>
This is my new code, it prints, but no total sum.
<?php
$number = $_POST['number'];
$i = 2;
$cal = 0;
$sum = 1;
$berekeningen = array();
while ($i <= $number) {
$sum .= "+" . $i;
array_push($berekeningen, $sum);
$i++;
}
print_r($berekeningen);
?>
Here's a solution:
$i = 1;
$number = 6;
while ($i <= $number) {
// generate array with values from 1 to $i
$array = range(1, $i);
// if there're more than 1 element in array - output sum
if (count($array) > 1) {
// 1+2+... part // sum of elements of array
echo implode('+', $array) . ' = ' . array_sum($array) . '<br />';
}
$i++;
}
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
I need to replace my "foreach" with "for", but actually I don't know how.
Here is the part of my php code:
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
echo "\n\r" . $v->id . "\n\r";
if (1) {
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
Thanks!
$r = "";
$j = 0;
foreach ($orgs as $k => $v) {
echo "\n\r" . $v->id . "\n\r";
if (1) { //you don't really need this, because it's allways true
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
if $orgs is an associative array, it becomes:
$r = "";
$j = 0;
for($i = 0; $i < count($orgs); $i++)
{
echo "\n\r" . $orgs[$i]->id . "\n\r";
$a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id);
$connection = $a_view_modl->getDbConnection();
}
better you do some checks first if you go for this solution.
if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal:
$i++; //if you want the increment afterwards
++$i; //if you want the increment before you read your variable
the same for decrements:
$i--; //decrement after reading the variable
--$i; //decrement before you read the variable
$r = "";
$j = 0;
for($i = 0 ; $i < count($orgs); $i++)
{
$v = $orgs[$i];
echo "\n\r" . $v->id . "\n\r";
if (1) {
$a_view_modl = ArticleView :: model($v->id, $v->id);
$connection = $a_view_modl->getDbConnection();
}
A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v.
Then $v has the value you are using in the snippet of code.
A for loop does only accept indexed arrays, and no associative arrays.
We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0.
$r = "";
$j = 0;
for ($i = 0; $i < count($orgs); $i++) {
echo "\n\r" . $orgs[$i]->id . "\n\r";
if (1) {
$a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id);
$connection = $a_view_modl->getDbConnection();
foreach ($orgs as $k => $v) {
// Your stuff
}
for loop
for ($i = 0; $i < count($orgs); $i++) {
// Your stuff ... use $orgs[$i];
}
I have been thinking for hours but i still cant get a solution for this
Basically what i want to do is to echo a separator inside a while, it should be something like this
$num = 1;
while($num < 3){
echo 'dog';
//function to stop while
echo 'separator';
//function to continue while
echo 'cat';
$num++;
}
I want to get this output
dog
dog
dog
separator
cat
cat
cat
I dont know if i explained myself well but hope you understand. Thank you very much in advance.
Update: I know i can make this with 2 while functions but is it possible to make it using only one while function?
definitely yes you can with one while ~function. :)
function OnlyOneWhileFunction($echoThis, $howManyTimes){
$i = 1;
while($i <= $howManyTimes){
echo $echoThis."\r\n";
$i++;
}
}
OnlyOneWhileFunction('dog', 3);
echo 'separator';
OnlyOneWhileFunction('cat', 3);
$num = 0;
$dogs = '';
$cats = '';
$seperator = 'seperator';
while($num < 3){
$dogs .= 'dog';
$cats .= 'cat';
$num++;
}
echo $dogs . $seperator . $cats;
Save the output of each of the dogs and cats then combine at end.
Alternate solution:
$items = array_reverse(array("cat","dog"));
$output = array();
while(count($items) > 0)
{
$item = array_pop($items);
$output[] = implode("\n", array_fill(0, 3, $item));
}
echo implode("\nseparator\n", $output);
You can replace \n with <br> for HTML output (or use nl2br).
Try this:
<?php
$num = 0;
while($num < 7){
if($num < 3)
echo 'dog';
elseif($num == 3)
echo 'separator';
elseif($num>3)
echo 'cat';
echo "<br>";
$num++;
}
?>
You would be better off using a C style for loop and a function call for this:
$recho = function($out, $limit) {
for ($x=0; $x<$limit; $x++) {
echo $out . "\n";
}
}
$recho('dog',3);
echo "seperator\n";
$recho('cat',3);
Put this inside a <pre> on a webpage to get your line breaks, or replace the "\n" with <br> tags.
The following code should work:
$num = 0;
while($num <= 6){
if($num < 3) echo 'dog<br/>';
else if($num == 3) echo 'separator<br/>';
else echo 'cat<br/>';
$num++;
}
Here's another approach if you wanted n number of options and assuming each option is iterated over the same number of times. I'd do some cleanup but this is a quick and dirty approach:
<?php
/**
* Loops items with separator every nth time
* #param array list of items
* #param integer number of iterations
* #param string separator text
*/
function loopItemsWithSeparator(array $items, $count, $separator) {
$items = array_reverse($items);
while(!empty($items)) {
$item = array_pop($items);
for($i = 0; $i < $count; $i++) {
echo $item . "\n";
}
if (count($items) > 0) {
echo($separator . "\n");
}
}
}
loopItemsWithSeparator(array('dog', 'cat', 'bird'), 3, 'separator');
?>
Struggling with this tournament fixtures algorithm.
The code is working perfectly but I need help inserting the data to mysql
I cant seem to access the $varables..
any tweaking by a php pro greatly appreciated ...
$teamnames = "Arsenal|Tottenham|Leeds|Man United|Liverpool";
# XXX check for int
print show_fixtures(isset($_GET['teams']) ? nums(intval($_GET['teams'])) : explode("|", trim($teamnames)));
function nums($n) {
$ns = array();
for ($i = 1; $i <= $n; $i++) {
$ns[] = $i;
}
return $ns;
}
function show_fixtures($names) {
$teams = sizeof($names);
print "<p>Fixtures for $teams teams.</p>";
// If odd number of teams add a "ghost".
$ghost = false;
if ($teams % 2 == 1) {
$teams++;
$ghost = true;
}
// Generate the fixtures using the cyclic algorithm.
$totalRounds = $teams - 1;
$matchesPerRound = $teams / 2;
$rounds = array();
for ($i = 0; $i < $totalRounds; $i++) {
$rounds[$i] = array();
}
for ($round = 0; $round < $totalRounds; $round++) {
for ($match = 0; $match < $matchesPerRound; $match++) {
$home = ($round + $match) % ($teams - 1);
$away = ($teams - 1 - $match + $round) % ($teams - 1);
// Last team stays in the same place while the others
// rotate around it.
if ($match == 0) {
$away = $teams - 1;
}
$rounds[$round][$match] = team_name($home + 1, $names)
. " v " . team_name($away + 1, $names);
}
}
// Interleave so that home and away games are fairly evenly dispersed.
$interleaved = array();
for ($i = 0; $i < $totalRounds; $i++) {
$interleaved[$i] = array();
}
$evn = 0;
$odd = ($teams / 2);
for ($i = 0; $i < sizeof($rounds); $i++) {
if ($i % 2 == 0) {
$interleaved[$i] = $rounds[$evn++];
} else {
$interleaved[$i] = $rounds[$odd++];
}
}
$rounds = $interleaved;
// Last team can't be away for every game so flip them
// to home on odd rounds.
for ($round = 0; $round < sizeof($rounds); $round++) {
if ($round % 2 == 1) {
$rounds[$round][0] = flip($rounds[$round][0]);
}
}
// Display the fixtures
for ($i = 0; $i < sizeof($rounds); $i++) {
print "<hr><p>Round " . ($i + 1) . "</p>\n";
foreach ($rounds[$i] as $r) {
print $r . "<br />";
}
print "<br />";
}
print "<hr>Second half is mirror of first half";
$round_counter = sizeof($rounds) + 1;
for ($i = sizeof($rounds) - 1; $i >= 0; $i--) {
print "<hr><p>Round " . $round_counter . "</p>\n";
$round_counter += 1;
foreach ($rounds[$i] as $r) {
print flip($r) . "<br />";
}
print "<br />";
}
print "<br />";
if ($ghost) {
print "Matches against team " . $teams . " are byes.";
}
}
function flip($match) {
$components = split(' v ', $match);
return "$components[1]" . " v " . "$components[0]";
}
function team_name($num, $names) {
$i = $num - 1;
if (sizeof($names) > $i && strlen(trim($names[$i])) > 0) {
return trim($names[$i]);
} else {
return "BYE";
}
}
I'm not entirely sure what you're hung up on (you should really be more specific in your questions, as specified by the FAQ), but I suspect it is a matter of scope.
When you set a variable within a function, that variable is only accessible within that function. For example:
function do_something() {
$a = 'something!';
}
do_something();
echo $a;
This should result in PHP notice telling you that PHP doesn't know what $a is in the scope that it is trying to echo. Now, if I modify this script...
$a = '';
function do_something() {
global $a; // Lets PHP know we want to use $a from the global scope
$a = 'something!';
}
do_something();
echo $a;
This will work and output "something!", because $a is being "defined" in the scope outside of the function.
You can read more about variable scope in the PHP documentation: http://php.net/manual/en/language.variables.scope.php
Now, something else you need to pay attention to is outputting user data. In your script, you take data straight from $_GET and print it out to the page. Why is this bad? Someone could inject some nice JavaScript into your page (or anything they wanted) and steal users' sessions. You should be using htmlspecialchars() any time you need to output a variable. Even if it is just a team name, you never know when some team will stick a ; or < or > or some other reserved character in there.
Finally, I strongly recommend not mixing your logic with your computation. Let your program figure everything out, and then loop through the data for your output. You should be able to save the entire data for this type of problem in a nice associative array, or some crafty object you come up with.