I am new to the world of coding as well as PHP and am wondering how I can use return when looping. For example I would like to return/display 1-10 however not use echo.
$start = 1;
$end = 11;
for($start; $start < $end; $start=$start+1) {
echo $start; //how can I use return?
}
Well, return will exit the function, so if you put return in a loop, the loop will only do one iteration (until the return statement).
You can collect all the values in an array and return the array:
function myFunction() {
$start = 1;
$end = 11;
$values = array();
for($start; $start < $end; $start=$start+1) {
$values[] = $start;
}
return $values;
}
That said, a function generating consecutive numbers already exists: range().
return is for sending the results of a function call back to the function or script that called it. It's the opposite of passing parameters to a function.
What you're doing is looping over a variable in the same scope, so return is not needed. Printing is done via echo or print. However, you may choose to build a value in that loop and print that once the loop is completed.
Additionally, if you're in a loop and you want to stop that loop immediately, use break; and if you want to skip the iteration you're on and go to the next one, use continue.
Here's some additional reading.
More clarification on continue. Say, for whatever reason, we don't want to do anything when $i is 6:
$start = 1;
$end = 11;
for ($i = $start; $i < $end; $i++)
// changed this to iterate over $i for readability/clarity
{
if ($start == 6)
{
// essentially, continue just skips this iteration of
// the loop, goes back to the top, iterates $i based on
// that third parameter in the for() declaration, and
// continues on.
continue;
}
echo $start; //how can I use return?
}
// output: 1234578910
just use
function foobar()
{
$output = '';
for ( $i = 1 ; $i <= 10 ; $i++ )
{
$output .= $i;
}
return $output
}
echo foobar();
You can achieve it by defining a variable you want to return inside and outside the loop with .=.
Here is a working example:
function my_function() {
// I am the variable to be return-ed
$k = "My World<br/>";
for ($z=1; $z<=3; $z++) {
$v = 'Here'.$z;
// I am the same variable but I am going inside the loop
$k .= $v . "<br/>";
}
//I am not always important to be here!
$k .= "Is Awesome";
// This is the show time..
return $k;
}
my_function();
Output:
My World
Here1
Here2
Here3
Is Awesome
Return will end the function that you are currently in. The scenario you have given us is not a good scenario to use the return function.
The example below will do the same as your code, but uses a function as well as your for loop. Hope this answeres your question.
$start = 11;
$end = 20;
for($start; $start <= $end; $start++){
echo calculateValue($start);
}
function calculateValue($value){
return $value - 10;
}
function loop_kec($ar_kec) {
$total_data = count($ar_kec) - 1;
//$return_kec = array();
for ($e = 0; $e < $total_data; $e++) {
$return_kec .= 'kecamatan = ' . "'$ar_kec[$e]'" . ' or ';
}
$return_kec .= 'kecamatan = ' . "'$ar_kec[$total_data]'";
return $return_kec;
}
Related
I need to add * in an array. This is how i do it in javaScript.
function makeStarString(grade) {
var starArray = [];
var starString = "";
for (var i = 0; i < grade; i++){
starArray[i] = "*";
starString = starString.concat(starArray[i]);
}
return starString;
}
The javascript version works fine but I cant make it work with php.
This is as far as i got with php.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < strlen($varGrade); $i++){
$starArray($i) = $star;
$starString = $starString.(starArray(i));
}
return $starString;
}
I get this error "Fatal error: Can't use function return value in write context" because of line $starArray($i) = $star;
The argument I send to the function is an Integer.
So the purpose of the function is that if i send a 5 to the function it will return *****
How can i fix my php function?
Use $starArray[$i] instead of $starArray($i) and starArray(i).
If you really need stars in an array, you don't need to use a loop:
$starArray = array_fill(0, $varGrade, '*');
and if you need to turn the array into a string:
$starString = implode('', $starArray);
But if you don't really ever need to use the array of stars, it would be easier to just use str_repeat:
str_repeat('*', $varGrade);
It would generally be a great idea to use strlen($varGrade) in a variable, because the foreach loop will have to count the length every iteration. This might bring performance issues.
Your $star variable is not defined, so I have no idea what you're trying to put there. Revise your own code.
Finally, you may use the .= operator to add something to existing string.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
$length = strlen($varGrade);
for ($i = 0; $i < $length; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
UPDATE
If you send an int to the function, you don't need strlen:
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
This code should work
function makeStarString($varGrade) {
$star = "*"; // star variable wasn't defined to.
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star; // [ ] instead of ( )
$starString .= ($starArray[$i]); // $a.=$b instead of $a=$a+$b, added the $ at the i and [ ] instead of ( )
}
return $starString;
}
Is this what you need?
function makeStarString($varGrade) {
$starString = '';
for ($i = 0; $i < $varGrade; $i++) {
$starString .= '*';
}
return $starString;
}
A few notes on my modifications.
I don't see why you need that $starArray array in the first place. So I skipped it.
I revised your indentation. Strange indentation can make very simple code seem much more complicated than it really is. :)
You should ask if $i < $varGrade, not if $i < strlen($varGrade). If you ask by strlen(), then you get the width of the number you enter. For example, strlen(55) is 2, strlen(555) is 3, strlen(5555) is 4 etc. - ignoring the fact that it's a number. You just want the for-loop to give you $varGrade many stars so there is no need for strlen().
As a detail, I've put used single-quotes instead of double-quotes for strings because they're lighter (PHP doesn't parse variables inside them).
I hope it helps.
How can I add to the array that I'm using foreach on?
for instance:
$t =array('item');
$c = 1;
foreach ($t as $item) {
echo '--> '.$item.$c;
if ($c < 10) {
array_push($t,'anotheritem');
}
}
this seems to produce only one value ('item1'). It seems that $t is only being evaluated once (at first time of foreach use) but not after it enters the loop.
foreach() will handle the array you pass into it as a static structure, it can't be dynamic as far as the number of iterations go. You can change the values by passing the value of the iteration by reference (&$value) but you can't add new ones in the same control structure.
for()
for() will let you add new ones, the limit you pass will be evaluated each time, so count($your_array) can be dynamic. Example:
$original = array('one', 'two', 'three');
for($i = 0; $i < count($original); $i++) {
echo $original[$i] . PHP_EOL;
if($i === 2)
$original[] = 'four (another one)';
};
Output:
one
two
three
four (another one)
while()
You can also define your own custom while() loop structure using a while(true){ do } methodology.
Disclaimer: Make sure if you're doing this that you define an upper limit on where your logic should stop. You're essentially taking over the responsibility of making sure that the loop stops somewhere here instead of giving PHP a limit like foreach() does (size of array) or for() where you pass a limit.
$original = array('one', 'two', 'three');
// Define some parameters for this example
$finished = false;
$i = 0;
$start = 1;
$limit = 5;
while(!$finished) {
if(isset($original[$i])) {
// Custom scenario where you'll add new values
if($i > $start && $i <= $start + $limit) {
// ($i-1) is purely for demonstration
$original[] = 'New value' . ($i-1);
}
// Regular loop behavior... output and increment
echo $original[$i++] . PHP_EOL;
} else {
// Stop the loop!
$finished = true;
}
}
See the differences here.
Thanks Scowler for the solution. It was posted in the comments and although he replied with an answer, it wasn't as simple as his first commented suggestion.
$t =array('item');
$c = 1;
for ($x=0; $x<count($t); $x++) {
$item = $t[$x];
echo '--> '.$item.$c;
if ($c < 10) {
array_push($t,'anotheritem');
}
$c++;
}
Works Great! count($t) is re-evaluated each time it goes through the loop.
what I want to do is run this for loop and within there is a foreach searching the positions. what I want to do is once there it returns false I want it to break and save the position of $i in a variable. I'm using simple_html_dom.php but I don't think that matters since this is more of a basic programming problem.
for($i = $0; $i < $20; $i++){
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
break;
}
}
//this is not valid, but essentialy this is what I want to do.
$stop = $i;
}
To break multiple levels in a loop you simply specify the levels, eg, break 2 - see the manual on break - http://www.php.net/manual/en/control-structures.break.php.
As such your code might work as
for($i = $0; $i < $20; $i++){
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
$stop = $i; // Set variable
break 2; // break both loops
// or alternatively force the outer loop condition to expire
//$i = 21; // Force the outer loop to exit
//break;
}
}
}
I have expanded to question to set $i = 21 to break the outer loop with a single break.
Untested code but syntax checked...
<?php
// Untested code...
// Assume that you WILL break out of the loops...
$currentForIdx = -1; // so we can test that 'for' loop actually ran
$quitLoops = false;
for($i = 0; $i < $20 && !quitLoops; $i++) {
$currentForIdx = $i; // in case we break out of the loops
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false) {
$quitLoops = true;
break;
}
}
}
// test $quitLoops and $currentForIdx to work out what happened...
?>
I havent tested this, but I would try something like this:
for($i = $0; $i < $20; $i++){
$stop = false;
foreach($html->find('div[class=cate_link]',$i) as $a){
if (strpos($a->plaintext,'+info') == false){
$stop = $i;
}
}
if ($stop !== false) {break;}
}
Write a class called math. It is to have one property called num. It also has one method (function) called factorial. This method is to start at 1 and multiply all of the integers to num. If num is 5 then you would multiply 1*2*3*4*5. Of course you are to do this in a loop.
Which loop should I use? For or do while? Also, do I need an inner loop?
I started with
For (i = 1; i <= 5; i++)
{
}
however, i'm stuck on what to do next...any suggestions?
You can do it using any loop. for loop can be converted to while and do .. while and opposite is true too.
for(i=0;i<5;i++)
is same as
i=0; while(i<5){i++;}
To to find the factorial you should multiply all the values from 1 to the number you want factorial of. So if $num = 5. Only one single loop is needed. You'd want to run this loop.
for($i=1;$i<$num;$i++){
$num*=$i;
}
I am not giving a full solution here because the question seems homework. If I give you full solution it will be spoon-feeding.
$result = 1;
$target = 5;
for ($i = 1;$ i <= $target; $i++)
{
$result *= $i;
}
echo $result;
or
$result = 1;
$target = 5;
while($target > 0) {
$result *= $target;
$target--; // You could do this all in one line, but for learners, this is clearer.
}
echo $result;
Each iteration you will want to multiply the total of the factorial by the value of $i
class Math {
public static function Factorial($factorial) {
$output = 1;
for($i = 2; $i <= $factorial; $i++)
$output *= $i;
return $output;
}
}
I've gotten to where I prefer the while(i--) loop:
<?php
class Math {
public $num = 0;
public function factorial() {
$result = 1;
$num = $this->num;
while ($num) {
$result *= $num--;
}
return $result;
}
}
$factor = new Math();
$factor->num = 5;
echo $factor->factorial();
?>
http://codepad.org/hUOgAoz2
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.