Auto-generate selectbox options array with PHP - php

I've been looking all over, but I can't find a specific case on this. I'm writing a plugin for a open-source software program, and am using it's $form class and functions to render my forms without needing to manually insert in HTML.
I'm trying to make a Minimum Age (#) and Maximum Age (#) selectbox fields, each ranging from 1 to 100. I know something like this can be quickly done with something like
for ($i = 1; $i <= 99; $i++)
And then apply $i to a form in your webpage. But since this is a MVC program, I am bounded (for the most part) to what classes, objects and functions are available. When making a selectbox's actual options in this program, you typically do something like:
$field->setOptions(array(
"Value"=>"Text Label",
rinse and repeat. However, since I'm trying to make a large list of numbers, I've been trying to find a way to somehow use range() or maybe array_push in place. I've tried the following thus far:
function forAge(){
for ($i = 1; $i <= 99; $i++){
$array[] = $i;
}}
$tminage->setOptions(array(
$array[]=>$array[]));
Or trying to pass the straightup "for" method and "range" method as the array's value. None of them work, either returning errors or displaying nothing on the selectbox. I'd like to know if there's any good way of working around this, or if it's a no-go because of the specific function wanting a simple array with a value and a label.

Maybe i am missing something here but there is what I would do :
$minAgeOptions = array();
for ($i = 1; $i <= 100; $i++){
$minAgeOptions[$i] = $i;
}
$tminage->setOptions($minAgeOptions);

Related

PHP - Multidimensional array recursion

I have an a problem I know how to tackle it but not 100% clear on what the implementation would look like.
This is a Symfony 3 app but the problem is a pure PHP one which involves some kind of recursion.
I have a multi-dimensional array which represents my nested form and and an errors that need to be mapped to a form field (that bit I know how to do).
Here is my array:
I need to loop over the children of fields recursively and when I reach the end of a node and it contains message key (just a way to confirm I have reached the error) then apply that to the form // apply to form here then remove that index/node so that the recursion doesn't go down that route again?
Can anyone help with the function that will do this. Like I said it is not important to know Symfony just help with the function that will recurs a mutli-dimensional array and remove that node before calling itself again.
My class at it stands but I can cut atleast 50% of this if I can just follow the array keys:
http://laravel.io/bin/ok5n9
Any help will be greatly appreciated :)
When looping through your array, use a for loop so you can easily manipulate indexes:
for($i = 0; $i < count($fields); $i++) {
// You can use $fields[$i] here for the current item
}
Using isset(), you can check if the message key exists in the fields array. If that is true, use the continue keyword to skip over the current item and continue with the next one.
It will look something like this, you can change it according to your needs:
for($i = 0; $i < count($fields); $i++) {
if (isset($fields[$i]['message')) {
// error exists...
continue;
}
// Delete the item from your array
unset($fields[$i]);
}
This is my fix. I created a form map which consists of the number of fields each with child arrays for the path to the element and the error.
I then loop over them and pass them through Symfonys mapViolation method in Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper.
Here is complete class:
https://gist.github.com/linxlad/3ec76c181f717fba532bf43484b7c970

Problems with For Loop syntax and variables

I have multiple variables named day1Name, day2Name, day3Name, and so on. I also have exercise_11_Name, exercise_12_name, etc.
I have a lot of those, and the value I want to save in those variables depends on user input.
I don't want to have to write $variableName = $_POST['name'] for every single one because it's a lot and a terrible practice. Therefore, I want to use a for loop so my code looks cleaner.
What I am trying to accomplish is something similar to this I believe:
for(i=0, i<10; i++)
{
$day[i+1]name = $_POST['day[i+1]name'];
$exercise_1[i+1]_name = $_POST['excName1[i]'];
}
I know the way I wrote it is not going to work though.
P.S. Where I wrote [i+1] is where I just need the number, for example, $day[i+1]name should become the variable $day1name when i=0. Where I wrote [i], for example excName1[i], that's an array in which I want to retrieve the value of that specific index.
I would really appreciate some help in this.
Thanks! =]
create an array named $day_name, and name your form fields day_name_1, day_name_2 etc
then in your loop:
$day_name[$i+1] = $_POST['day_name_' . ($i + 1)]
do the same with the exercise variables.
I assume it is php, so your loop variable has to be $i, not i
The solution you are asking for is called somewhat variable variable or variable expansion and goes on like this:
for($i=0; $i<10; $i++)
{
$d=$i+1;
${"day{$d}name"} = $_POST["day{$d}name"];
${"exercise_1{$d}_name"} = $_POST["excName1{$i}"];
}
However I encourage you to look at "array" which is somehow what #Bart suggested above, which is probably a better way of organizing your data around.

How to assign PHP-variables by using two arrays

I'm trying to use a for-loop which loops through two arrays.
My first one looks like this:
$pos = array("Yada Yada", "Boom Boom");
And the second one looks like this:
$pos_var_names = array("yada", "boom");
My goal is to use a for-loop to automatically loop through both arrays at the same time and for example set:
$yada = "Yada Yada";
How do I do this in the most efficient way?
Sorry if I'm missing something obvious. Have been coding for a couple of hours straight and I'm feeling a bit dizzy.
Best regards!
You could use a for-loop:
for ($i = 0; $i < count($pos); $i++)
${$pos_var_names[$i]} = $pos[$i]; // variable variables
But it is more elegant like this:
extract(array_combine($pos_var_names, $pos));
This just makes an $varname => $pos array (see also the documentation for array_combine which is then extract()'ed.
But generally, it's better to just have an associative array instead of using tons of variables. It just will fill your variable scope with useless variables which might conflict with other variables you have.

PHP - How Can I Create Variable Names Within a Loop?

My goal is to have a loop where variable names are created. Such as:
$variable1
$variable2
$variable3
and assigned values within the loop. For instance, a for loop from 1 to 7 produces the variables $variable1, $variable2, $variable3, .etc, each with the value of the iterator.
There are several ways. One is via a string and a double $, but I don't like this method. A programmer could easily remove the double $ (seeing it as a typeo).
for($i = 0; $i <= 7; $i++) {
$name = "variable{$i}";
$$name = "foo";
}
The best approach is the explicit statement.
for($i = 0; $i <= 7; $i++) {
${"variable$i"} = "foo";
}
With the explicit inline string there is no doubt about the intent of what you're doing. Another PHP programmer will not alter the code by mistake.
You should use an array for this:
for($i = 1; $i <= 7; $i++) {
$variable[$i] = $i;
}
Edit: to clarify, you should use an array because there's no code (to my knowledge) which will accept $variable1 but not $variable[1]. Dynamically generating variable names is all kinds of wrong.
Just to expand on what others have said about why this is a technique best avoided: variable names exist solely for use by the programmer; they have no relationships or properties according to the language's runtime. As such, a collection of related variables should be put into a variable representing some appropriate container - in the case of PHP, its incredibly flexible "array" type.
Whenever the issue of dynamically named variables is raised, it is usually because somebody thinks it is a solution to a particular problem, but it generally leads to more problems than it solves - for instance, once part of a program starts dynamically naming variables, everywhere that wants to use those variables now also has to dynamically name them; finding out which items are actually set becomes unnecessarily complex, and so on.
There are a very few contexts where variable-variables are useful, for certain kinds of debugging and meta-programming, for example, but like goto, their presence in the language should not mean you don't try every other possible solution first.
999 times out of 1000, though, if you find yourself wondering how to dynamically create variable names, you should reframe the question: what are you actually trying to achieve, and what is the best solution to that problem. If some existing / 3rd-party code has been built using this pattern (and presumably also global variables), it may be best to patch or wrap it rather than propogating the mis-design into your own code. (Admittedly, a wrapper will still need to know how to declare the dynamic variables.)
If you had an associative array i'ld prefer using the extract() method. Check it out here
for example
<?php
/* Suppose that $var_array is an array*/
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape";
?>
the above code would output,
blue, large, sphere, medium
In case any one wants to do this through an object:
<?php
$x = 1;
while($x <= 4){
echo $q->{"a$x"};
$x++;
?>
Thats no possible since variable cannot be create in run time

how to run the php script n times with different set of parameters

I want to run one php script n number of times and I would be passing some variable to that script.
I have tried to loop inside the scripe but thats not working. is there any way so that I can run pho script again and again in loop. I would be passing one variable also and that scrip have to work on that variable. is there any way ?
If I understand the question, and you just want to loop over some PHP code a certain number of times, there is no reason a standard for loop would not work:
for($i = 0; $i < number_of_times; $i++) { ...code... }
You should refactor your code into a function:
function myFunction(args...)
{
//your original script here
}
And you can then use a for loop to repeatedly run it with different arguments.
for(i = 0; i < 10; i++)
{
//collect different arguments
myFunction(args);
}

Categories