Function With/Without Passing an argument - PHP - 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

Related

How to echo some code inside a while loop?

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');
?>

How can I print integer in triangle form

I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

PHP altering row output based on different column

I have some data outputting via PHP/MySQL. It's simply a list of Chinese characters that corresponds to a certain string.
$i = 0;
while ($i <= $x) {
echo "<div class=\"char-option\">" . $results[$i]['mainchar'] . "</div>";
$i++;
}
I have another row with a character ranking in it, about 20% of the characters have a ranking. I would like to:
Change the class to "char-option char-common" for the character with the highest ranking.
Don't change the class if none of the characters have a ranking.
Thanks in advance.
Step 1: Determine, WHICH character has the highest rank.
$high = -1, $hrank = 0;
for($i = 0; $i <= $x; ++$i) {
if(isset($results[$i]['rank']) && $hrank < $results[$i]['rank']) {
$high = $i;
$hrank = $results[$i]['rank'];
}
}
Step 2: With the information, which has the highest character ranking, we can determine, who gets the normal class and who gets the additional class.
for($i = 0; $i <= $x; ++$i) {
$class = "char-option"; //Default class
if($i == $high) $class .= " char-common"; //Adds the second class for the highest ranked character.
echo "<div class=\"$class\">" . $results[$i]['mainchar'] . "</div>";
}
The -1 in $high makes sure, that the class will not be changed, unless there is a ranking somewhere within the list.
set your ranking in the result and do in this way.
$i = 0;
while ($i <= $x) {
if ($results[$i]['highest_ranking'] == 1) {
$class = "char-option char-common";
} else {
$class = "char-option";
}
echo "<div class=\"$class\">" . $results[$i]['mainchar'] . "</div>";
$i++;
}

Custom Break Command/Function with create_function() in 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 ?

Categories