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.''];
}
Related
I want clear $_POST array content fully, all examples what I see in internet, looks like this:
if (count($_POST) > 0) {
foreach ($_POST as $k=>$v) {
unset($_POST[$k]);
}
}
Tell please, this variant will be not more better? (Point of view as saving resources)
if (count($_POST) > 0) {
$_POST = array();
}
or not ?
Yes, that is fine. $_POST is just another variable, except it has (super)global scope.
$_POST = array();
...will be quite enough. The loop is useless. It's probably best to keep it as an array rather than unset it, in case other files are attempting to read it and assuming it is an array.
To unset the $_POST variable, redeclare it as an empty array:
$_POST = array();
The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.
How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?
It may appear to be overly awkward, but you're probably better off unsetting one element at a time rather than the entire $_POST array. Here's why: If you're using object-oriented programming, you may have one class use $_POST['alpha'] and another class use $_POST['beta'], and if you unset the array after first use, it will void its use in other classes. To be safe and not shoot yourself in the foot, just drop in a little method that will unset the elements that you've just used: For example:
private function doUnset()
{
unset($_POST['alpha']);
unset($_POST['gamma']);
unset($_POST['delta']);
unset($_GET['eta']);
unset($_GET['zeta']);
}
Just call the method and unset just those superglobal elements that have been passed to a variable or argument. Then, the other classes that may need a superglobal element can still use them.
However, you are wise to unset the superglobals as soon as they have
been passed to an encapsulated object.
You can use a combination of both unset() and initialization:
unset($_POST);
$_POST = array();
Or in a single statement:
unset($_POST) ? $_POST = array() : $_POST = array();
But what is the reason you want to do this?
To answer "why" someone might use it, I was tempted to use it since I had the $_POST values stored after the page refresh or while going from one page to another. My sense tells me this is not a good practice, but it works nevertheless.
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.
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.
I'm new to PHP, I have this code:
if(!$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value']){
$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'] = $default_city;
}
it's working but I don't like it to be that long, so I change:
$form_location = $form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'];
if(!$form_location){
$form_location = $city;
}
Then it's not working, why?
It's because when you assign $form_location, it is making a copy of the data. In order for both variables to "point" to the same data, you would need to use the reference operator, example:
$var = &$some_var;
and in your case:
$form_location = &$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'];
if(!$form_location){
$form_location = $default_city;
}
http://php.net/manual/en/language.references.php
Because your code is assigning to $form_location, but not the actual value in the array.
The assignment makes $form_location refer to something different. The fact that its former value happened to be copied out of an array is irrelevant.
In C/C++, you could do something like this using pointers, but most higher level languages don't support it since it tends to be error prone.
Anyway, you could set a variable to the innermost array, since arrays are stored by reference. This would reduce the amount of code you need, while avoiding the problems introduced by taking a reference directly to an array element.
$form_location = $form['profile_hunter']['field_profile_hunter_location']['und'][0]['value']['#default_value'];
if(empty($form_location)){
$form['profile_hunter']['field_profile_hunter_location']['und'][0]['value']['#default_value'] = $city;
}
You should probably use 'empty', that is a Drupal convention. Also "0" is not a string, but a number, so you don't need quotes around it.
Got the answer! Thanks to Tony!
It should be
$form_location = &$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'];
The "&" means to pass by reference, without it would be to pass by value.
I'm new to OOP and want to revamp this function to get rid of using globals.
function CatchListing() {
$parseform = array('itemnum','msrp','edprice','itemtype','box','box2','box25','box3','box4','box5','box6','box7','itemcolor','link');
foreach ($parseform as $globalName) {
$GLOBALS[$globalName] = mysql_real_escape_string($_POST[$globalName]);
}
}
I was told to use array_map & then extact, but I am not sure of how to structure this.
function CatchListing() {
$_POST['listing'] = array_map('mysql_real_escape_string', $_POST);
$nst = extract($_POST['listing']);
}
(listing is the form name btw)
Thanks
Be VERY careful about using extract with externally inputted values as from $_GET and $_POST.
you're much better off extracting the values manually to known values.
It's far too easy for an extract from _GET or _POST to clobber existing variables.
There are so many things to say and Jonathan makes a very good start. Every time the user has the opportunity to play with your internal data and you don't check them, there is a huge "opportunity" (depends on the view..) that something goes wrong. Here is another approach on how to "maybe" get where you want to go:
<?php
function Sanitize($string){
return mysql_real_escape_string(trim($string));
}
function CatchListing(){
foreach($_POST as $key => $value) {
$key = Sanitize($key);
$value = Sanitize($value);
if($key && $value && !$GLOBALS[$key]){ /* prevent overwriting existing globals*/
$GLOBALS[$key] = $value;
}
}
}
global $nice;
$nice = "working";
CatchListing();
print_r($GLOBALS);
?>
To be honest, it still has not really anything to do with OOP and furthermore should be seen as a procedural approach. Personally I would use an additional and reusable function to "sanitize" the input, because you never know, if someday you want to change your database or the "escape" function and then you exactly know where to look for possible changes. Ah one more thing: Are you certain that you don't know all the possible names of all the variables you have to expect? Maybe you can predetermine them and put them in another array and check each user supplied argument with in_array.
To completely get rid of the usage of globals in your code, and also to make it much better overall, you can do something along these lines:
stop using $_POST, as it's a superglobal. When code needs values from superglobals, pass them as parameters
don't store values into $GLOBALS. If you need to return more than one value, consider returning an object or an array
Here's how I think I would modify your code to improve it:
function CatchListings($listings) {
$filteredListings = array_map('mysql_real_escape_string', $listings);
//I assume you only need the values in the array in the original snippet,
//so we need to grab them from the parameter array and return only that
$requiredListings = array();
$requiredKeys = array('itemnum','msrp','edprice','itemtype','box','box2','box25','box3','box4','box5','box6','box7','itemcolor','link');
foreach($requiredKeys as $key) {
$requiredListings[$key] = $filteredListings[$key];
}
return $requiredListings;
}
To use this function, you simply do $result = CatchListings($_POST);. Same result, no globals used.
There is one thing to consider, though. It may not be best possible form to just pass a randomly filled array (ie. $_POST) to the function, and expect it to contain specific keys (ie. $requiredKeys array). You might want to either add logic to check for missing keys, or process the post array before passing it.