is it posible to auto increment variable name after a while loop? - php

I need to create a php file with a hundred variables, which are all identical except for their id.
PHP Code
$var1 = get_input('myvar1');
$var2 = get_input('myvar2');
$var3 = get_input('myvar3');
$var4 = get_input('myvar4');
...
$var30 = get_input('myvar30');
I wonder if it is possible to create only one line as a model, and is replicated 30 times?

I think you are looking after something like this :
$vars = [];
for($i = 1; $i <= 30; $i++) {
$vars[] = get_input('myvar' . $i);
}

this is a job for arrays
$var = array_fill(1, 30, 'myvar');
use the array key as your "id"

Why bother with arrays when you can create the variables like so. The variables names are also set dynamically just like the values.
for ($i = 1; $i <= 100; $i++) {
${'var' . $i} = get_input('myvar' . $i);
}

Related

How to create empty string using for loop PHP

I'm trying to create for loop giving strings empty value. How I can do it?
for ($i = 1; $i <= 24; $i++) {
$b2_ch_v = ${'b2_g_v_'.$i}['id'];
$$b2_ch_v = '';
}
/*
result should be:
$b2_g_v_1['id'] = '';
$b2_g_v_2['id'] = '';
[...]
$b2_g_v_24['id'] = '';
*/
Don't use variables named like $x1, $x2, $x3. You almost always want to use arrays instead. In this case, you can use an indexed array of associative arrays. This is sometimes also called a two-dimensional array.
for ($i = 0; $i < 24; $i++) {
$b2_ch_v[$i] = ['id' => ''];
}
Then your first element becomes:
$b2_ch_v[0]
And its named elements can be referred to via:
$b2_ch_v[0]['id']
You're setting $b2_ch_v to the current contents of the id element of the array, not a reference to the array element. You need to refer to the array index in the assignment.
for ($i = 1; $i <= 24; $i++) {
$b2_ch_v = 'b2_g_v_'.$i;
${$b2_ch_v}['id'] = '';
}
var_dump($b2_g_v_1); // => array(1) { ["id"]=> string(0) "" }
You don't actually need the variable, you can do the calculation in the assignment:
${'b2_g_v_'.$i}['id'] = '';
But it's best to avoid variable variables in the first place, and use arrays instead as in the other answer.

Count up from one var to another

Hey guys a quick question in php.
This probably is pretty simple I'm not sure but I would like to know how to count up from one variable to another. So say I have the value 5 and the value 9 in the other I would like the PHP code to count each number and store in a array.
e.g
$var1 = 5;
$var2 = 9;
it should store each value (5,6,7,8,9) in a array so i can access them like so arrayname[1]
Thanks in advance
This should do it for you
$var1 = 5;
$var2 = 9;
foreach (range($var1, $var2) as $number) {
echo $number;
}
If you want to store it as an array then
$number = range($var1, $var2);
Another alternative:
$var1 = 5;
$var2 = 9;
$numbers = array();
for ( $i=$var1; $i <= $var2; $i++ ) {
$numbers[] = $i;
}
Then the variable $numbers should be the array that you want.

use variable name in code processing php like $number01 use it value, not name

so better will be example (so hard to give a title to this problem)
imagine I have variables in php like
$number1 = 10;
$number2 = 30;
$number3 = 23;
.. and so on..
and I just want to make an arithmetic average but not like
($number1 + $number2 +$number3)/3 because it is so much typing (having more than only 3 numbers)
but use something like
$temp=0;
for ($i=1;$i<50;$i++){
$temp=$temp+$number."$i"; <- this is what I don't know how to define..
}
and similar, how to echo all values for numbers like
for ($i=1;$i<50;$i++){
echo $number.$i; <- but this is not working..
}
I hope I have described it good, thank you for your help!
It can be done with variable variables but it's ugly:
$temp=0;
for ($i=1;$i<50;$i++){
$temp=$temp+(${$number.$i});
}
There is a limitation with the variable variables which is you don't know how high the number goes. You would also need to check if the variable is set first. A better solution is to store each of the variables in an array, which you can easily iterate over:
$arr = array();
$arr[] = 10;
$arr[] = 30;
$arr[] = 23;
$temp = 0;
foreach($arr as $val)
{
$temp += $val;
}
$number = array(10,20,30);
echo array_sum($number);
the other solution doing the same with for loop
$number = array(10,20,30);
$count = count($number);
$sum = 0;
for($i = 0; $i < $count ; ++$i) $sum += $number[$i];
or foreach
$number = array(10,20,30);
$count = count($number);
$sum = 0;
foreach($number as $n) $sum += $n;
there are a lot of methods to add items to array for example
$number = array(10,20,30);
$number = array();
$number[] = 10; $number[] = 20; $number[] = 30;
$number[0]= 10; $number[1] = 20; $number[2] = 30;
$number = array();
array_push($number, 10, 20, 30);
But the most simple and working solution is to use arrays and array_sum() function.
Array sum - Calculate the sum of values in an array
It's probably better to put all these values into an array instead of different variables. This makes adding later easier and allows you to loop like:
foreach($myArray as $number){
echo $number;
}
If you still want/need to use variables you can use variable variables:
$temp=0;
for ($i=1;$i<50;$i++){
$numberName = "number".$i;
$temp=$temp + $$numberName;//Note the $$ syntax.
}
$$foo will be the value of the variable with the name stored in $foo.
A final note. Be careful with variable variables, as they can lead to messy or unreadable code.
use an array
$number[0] = 10;
$number[1] = 20;
$number[2] = 23;
for ($i=1;$i<count($number);$i++) {
echo $number[$i]; //now this works.
}

How to sort it better?

I have 2 arrays, both are multidimensional with same number of elements and same values, which are on different positions (those values are actually ID-s from my database, so one ID appears only once). How can I sort second array with values which are in first array?
For example - if first array looks like:
$array1[0][0] = 1;
$array1[0][x] = it doesn't matter what's here
$array1[1][0] = 4;
$array1[1][x] = it doesn't matter what's here
$array1[2][0] = 3;
$array1[2][x] = it doesn't matter what's here
...
how to sort second array so it would have same values as array1 on indexes [0][0], [1][0], [2][0], etc.
How I could solve problem is:
$i=0
while ($i < (count($array1)-2)){ // * check down
$find_id = $array1[$i][0];
// here I need to search for index of that ID in other array
$position = give_index($find_id, $array2);
// swapping positions
$temp = array2[$i][0];
$array2[$i][0] = $array2[$position][0];
$array2[$position][0] = $temp;
// increasing counter
i++;
}
function give_index($needle, $haystack){
for ($j = 0, $l = count($haystack); $j < $l; ++$j) {
if (in_array($needle, $haystack[$j][0])) return $j;
}
return false;
}
*There is only -2 because indexes start from 0 and also for the last element you don't need to check since it would be automatically sorted by last iteration of while-loop.
I don't find this solution good as I think that this is quite simple issue (maybe it's not even correct). Is there easier way in PHP that I'm missing?
This is the most efficient way I can think of:
function swap(&$a, &$b) {
$t = $a;
$a = $b;
$b = $t;
}
function find_index($id, $array, $from = 0) {
$index = false;
for ($i = $from, $c = count($array); $i < $c; $i++) {
if ($array[$i][0] == $id) {
$index = $i;
break;
}
}
return $index;
}
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
if ($array1[$i][0] != $array2[$i][0]) {
$fi = find_index($array1[$i][0], $array2, $i);
swap($array2[$i][0], $array2[$fi][0]);
}
}
What changes from yours?
I've defined a swap() function in order to swap any variable. That doesn't cost anything and makes everything look nicer. Also you can reuse that function later if you need to.
In the find_index (give_index in your code) we stop the loop once we find the correct index. Also we avoid the cost of an in_array function call.
We modified the find_index function to start only from the part of the array we haven't checked yet. Leading to a way more efficient way of scan the array.
In the for loop (a while loop was just wrong there) we stored the count of the array once, avoiding multiple calls.
Also we swap the $array2 values only if they are in the wrong place.
Other improvements
If you know anything else of the $array2 array you can make this even more performant. For example if you know that indexes are alternated like in $array1 you can change the main for loop from:
for ($i = 0, $c = count($array1); $i < ($c - 2); $i++) {
to
for ($i = 0, $c = count($array1); $i < ($c - 2); $i+2) {
(notice the $i+2 at the end) And you could do that in the find_index function as well.
Look into usort (http://php.net/manual/en/function.usort.php).
It provides a simple way to sort arrays using a user provided comparison function.

What's the fastest way to populate an array with numbers in PHP?

What's the fastest way to populate an array with the numbers 1-100 in PHP? I want to avoid doing something like this:
$numbers = '';
for($var i = 0; i <= 100; $i++) {
$numbers = $i . ',';
}
$numberArray = $numbers.split(',');
It seems long and tedious, is there a faster way?
The range function:
$var = range(0, 100);
range() would work well, but even with the loop, I'm not sure why you need to compose a string and split it - what's wrong with simply:
$numberArray = array();
for ($i = 0; $i < 100; $i++)
$numberArray[] = $i;

Categories