Get a sequence with difference using for loop in PHP - php

How to get a sequence like (50 difference)
100,150,200,250,.....,900.
using 2 values (100 & 900).
My try gets an increment with 50,
for($i=100;$i<900;$i++)
{
$ii=$i+50;
echo '<option value="'.$ii.'">'.$ii.'</option>';
}

Go simple like this:
for($i=100;$i<=900;$i+=50)
{
echo '<option value="'.$i.'">'.$i.'</option>';
}
Also if you wanted to include 900, use <= not just <
Your Eval

Another option: use range() (http://php.net/manual/en/function.range.php)
$sequence = range(100, 900, 50);
foreach ($sequence as $step) {
echo '<option value="' . $step . '">' . $step . '</option>';
}
This is less memory efficient than a for loop, but I believe it is more readable. In PHP 5.5 you can make it both efficient and readable by defining a generator version of range (a-la the Python xrange). See the first example here: http://php.net/manual/en/language.generators.overview.php

Related

Convert SQL query with COALESCE and LEFT JOIN to PHP [duplicate]

This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 3 years ago.
Why does the following code output 0?
It works with numbers instead of strings just fine. I have similar code in JavaScript that also works. Does PHP not like += with strings?
<?php
$selectBox = '<select name="number">';
for ($i=1; $i<=100; $i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox += '</select>';
echo $selectBox;
?>
This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
In PHP use .= to append strings, and not +=.
Why does this output 0? [...] Does PHP not like += with strings?
+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.
More about operators in PHP:
Reference - What does this symbol mean in PHP?
PHP Manual – Operators
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus a (.) period is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>

Multilanguage and select option

I'm working with a multi-language site, and there is an HTML select element with 100 choices. The code looks like this:
<option value="1"><? echo $lang['CARGOTYPE_1']; ?></option>
So system insert into mysql table "type" number "1", or number "2" pr...
But when I select number from mysql, I need to change number to word.
With if, else I can change its meanings:
If($type == 1) { echo $lang['CARGOTYPE_1']; } elseif($type == 2){ echo $lang...
But the problem is, that code will be very long...
Any smart solutions for my problem?
If you know number of choices, use for cycle for that.
for ($i = 1; $i <= 30; $i++) {
echo '<option value="' . $i . '">' . $lang['CARGOTYPE_' . $i] . '</option>';
}
I am not sure what you want... If you want to "echo" something with arguments, you can do something like :
echo $lang['CARGOTYPE_'.$type];
But, is that you need ?

Using dynamic variables with isset()?

I have a loop that has a dynamic variable in it, eg:
while(i < 10){
echo ${"dynamic" . $i . "var"};
$i++;
};
I want to only echo the variable if the original var (say $dynamic3var) is set so I add:
while(i < 10){
if(isset(${"dynamic" . $i . "var"})){
echo ${"dynamic" . $i . "var"};
$i++;
};
};
However this wont work as its still picking up $i.
Does anyone know a correct way of doing this?
Since global variables are bad ideas you should rethink your code. A plain refactoring would be to use an associative array (even if it remains a global variable at the first step). Then you could work with
if( isset($dynamic[$i]) ) ...
Why are Globals evil? Read this: http://tomnomnom.com/posts/why-global-state-is-the-devil-and-how-to-avoid-using-it
Try this:
while($i < 10){
$label = "dynamic".$i."var";
if(isset($$label))
echo $$label;
$i ++;
};

Run A PHP function only 30% of Time

I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";

How do I make a foreach loop display items on more than one column?

I'm trying to modify a joomla module and I have a small problem (which is not joomla related, thus no code necessary).
I have a foreach loop which has a block of code in it which displays an article. It repeats itself as many times as you set it up in the admin panel. I want to add the feature that makes this module display items on more than 1 column. All I need is the perk, I think I have everything else covered.
Basically how do I modify a simple foreach loop so that it displays articles on more than one column?
Instead of this
a
b
c
d
e
I want this
a ........ d
b ........ e
c
You can get the count of results and work from the middle if you're sticking with tables
$half_count = floor(count($entries) / 2);
for($i=0;$i<$half_count;$i++)
{
echo '<tr>';
echo '<td>' . $entries[$i] . '</td>';
echo '<td>' . (isset($entries[$half_count + $i]) ? $entries[$half_count + $i]: '') . '</td>';
echo '</tr>';
}
Here a simple way to do it :
php > $arr = array(1,2, 3, 4, 5, 6, 7, 8, 9, 10);
php > for ($i=0; $i<count($arr); $i+=2) { print $arr[$i] . "\t" . $arr[$i+1] . "\n"; }
1 2
3 4
5 6
7 8
9 10
As far as I know, you won't be able to do it with a foreach statement but with a for.
For example:
$iterations = (count($array_of_items) % 2) ? (count($array_of_items) / 2) + 1 : count($array_of_items) / 2;
for ($i = 0; $i <= $iterations; $i++) {
if (isset($array_of_items[$i+3]))
echo $array_of_items[$i].'........'.$array_of_items[$i+3];
else
echo $array_of_items[$i];
}
Really simple code without so little info but could make the trick!
Instead of outputting in the for loop, I would create two arrays of the articles in the for loop. Then loop through those arrays to create your columns outside of the main loop.
You have little info in the question, but here's something you could use
$arr = array("a","b","c","d","e","f");
for ($i = 0; $i<count($arr); $i++){
echo $arr[$i]." ". $arr[$i+3] ."\n";
if($i == 2){ break;} //Modify 2 as more alphabets are added
}
Outputs
a d
b e
c f
For a generic solution, assuming a packed array....
function show_table($data, $columns)
{
$items=count($data);
$iters=$items/$columns + ($items % $columns) ? 1 : 0;
for ($y=0; $y<$iters; $y++) {
for ($x=0; $x<$columns; $x++) {
$offset=$y*$columns + $x;
if ($offset<$items) print $data[$offset] . ' ';
}
print "\n";
}
}

Categories