How to assign PHP-variables by using two arrays - php

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.

Related

How to set array's two keys with same value? (PHP)

There exists such:
$var1 = $var2 = "blabla";
but is there a way to set similar inside array? like:
array(
'key1'='key2' => "blabla",
...................
)
p.s. I dont need outside of array functions, like array_fill_keys or etc.. I want inside-array solution (if it exists).
You can set multiple array values of an array like this. Perhaps it even works without the first line.
$a = array();
$a['key1'] = $a['key2'] = 'blablabla';
Or initialize the desired keys using this awkward syntax:
$a = array_fill_keys(array('key1', 'key2'), 'blablabla');
Although the second one works, I wouldn't use it. Better to use a couple of characters extra or even separate lines than to write such a weird line which doesn't have much benefit apart from saving a tiny bit of code.

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 get size_of $_GET

I want to get the number of values that were submitted via my $_GET. I'm going to be using a for loop and every 7 are going to be saved to a class. Does anyone know how to find the Size_of the $_GET array? I looked through this info $_GET Manual, but don't see what I'm looking for.
This is a code snippet that I started in the class that I go to after the submit.
for($i=0;$i<$_GET<size>;$i++) {
$ID = $_GET["ID"][$i];
$Desc = $_GET["Desc"][$i];
$Yevaluation = $_GET["Yevaluation"][$i];
$Mevaluation = $_GET["Mevaluation"][$i];
$Cevaluation = $_GET["Cevaluation"][$i];
$Kevaluation = $_GET["Kevaluation"][$i];
$comment = $_GET["comment"][$i];
//saving bunch to class next
}
$_GET is an array. Like any other array in PHP, to find the number of elements in an array you can use count() or its alias sizeof().
count($_GET["ID"])
could work. However, then you have to be sure that each index contains the same number of elements.
More secure would be
min(count($_GET["ID"]), count($_GET["Desc"]), ...)
With array_map this can probably be shortcut to something like:
min(array_map(count, $_GET))
Try thinking through the last one, if it seems difficult to you. It's called functional programming and it's an awesome way to shortcut some stuff. In fact array_map calls another function on each element of an array. It's actually the same as:
$filteredGet = array();
foreach ($element in $_GET) { // this is the array_map part
$filteredGet[] = count($element);
}
min($filteredGet);
Even better would be a structure where $i is the first level of the array, but I think this is not possible (built-in) with PHPs $_GET-parsing.

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

Adding increamental variable number to a variable

I am trying to create a loop that creates variables using the increment/count number:
$names = 4;
for($it=0;$it<$names;$it++){
$NAME{$it} = $_REQUEST['NAME'.$it.''];
$SURNAME{$it} = $_REQUEST['SURNAME'.$it.''];
$AGE{$it} = $_REQUEST['AGE'.$it.''];
}
My issue is that instead of getting $NAME0, $NAME1 etc, I am getting an array (so $NAME[0], $NAME[1] and so on).
How would I use the loop to get all the info in $NAME0, $NAME1, $NAME2, $SURNAME1, $SURNAME2 $SURNAME3, $AGE1, $AGE2, $AGE3?
Thanks :)
You don't want variables with related names; using an array is much simpler. In this case, $NAME0 is the same as $NAME[0], except you can do a lot more things with $NAME[0] than you can with $NAME0. Stick with the array, learn to use it; don't reinvent the wheel.
Generally speaking, this would be dangerous for super-globals (e.g. $_REQUEST) without serious forethought.
However, this is an excellent use case for the underused PHP function extract().
If you were to use it in such a case, I'd strongly recommend setting the additional parameters with the EXTR_PREFIX_ALL flag.
I agree with the others about using an array, much better but if that's not what you want, try adding an underscore to the variables... May not be "perfect" but won't create an array:
$names = 4;
for($it=0;$it<$items;$it++){
$NAME_{$it} = $_REQUEST['NAME'.$it.''];
$SURNAME_{$it} = $_REQUEST['SURNAME'.$it.''];
$AGE_{$it} = $_REQUEST['AGE'.$it.''];
}

Categories