Using a variable key name to access $_GET / $_POST data in php - php

I need to use a variable as the key to access the $_GET data.
Is it possible?
This is my code:
if($_GET){
for($i=0;$i<9;$i++){
echo $_GET["value0"];
print_r(${'_GET["value'.$i.'"]'});
}
}
But it doesn't work.
I need to get $_GET['value0'], $_GET['value1'], and so on.

You should check the existence of each value with isset() before trying to access it. Also in php you don't need any complex string manipulations to put your variable in a string. You can just literally "put your variable in the string":
for($i = 0; $i < 9; $i++) {
if(isset($_GET["value$i"])) {
echo $_GET["value$i"];
}
}

Related

How do you print a variable in PHP that's either one element of an array, or the whole variable if it's not an array

Say I have $exampleVariable, which I want to print. $exampleVariable may be an array, in which case I have this set up to get the right array element, which I can then print with print $exampleVariable[$i].
if ($_GET) {
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} elseif (is_array($exampleVariable)) {
$i = 0;
} else {
$i = "";
}
My problem is that last else, if $exampleVariable is NOT an array, because then I get print $exampleVariable[] which doesn't work. So is there something I can put as $i to print the whole variable?
Alternatively, I considered including the brackets in $i, so I'd have for example $i = [0];, but in that case I don't know how I'd print it. $exampleVariable$i certainly won't work.
I have a good number of variables besides $exampleVariable I'll need to print, all with the same $i or lack thereof, so I'd like to not have to do anything longwinded to set each of them up individually.
This sounds way more complicated than I feel like it should, so hopefully it makes sense!
You can always do a nifty thing that is called type casting. That means, that you can always make a variable an array even if it is not, by prepending its name by (array):
$exampleVariable = (array)$exampleVariable;
So you don't need three if branches at all:
if ($_GET) { 
$i = array_search($_GET["exampleQueryString"], $exampleVariable);
} else {
$i = 0;
$exampleVariable = (array)$exampleVariable;
}
You could apply the (array) cast, which will have no effect if the target is already an array:
$i = array_search($_GET["exampleQueryString"], (array)$exampleVariable);

PHP- concatenate string with iterator to get original variable name

I have 20 variables with name $encode1,$encode2....,$encode20.
Now, I want to print these variable in the for loop by combining $encode.$1 to achive variable $encode1.
Loop example:
for($i =1;$i<=20;$i++)
{
$echo = $encodedImage.$i; => What to do here?
}
How could I access the names by using iterator?
Plus, I don't want to create an array. I just want to access them directly dynamically.
I haven't found any answer on stackoverflow regarding this topic. If there is any, please share me the link. Thanks!
using variables variable to achieve such a approach
Sometimes it is convenient to be able to have variable variable names.
That is, a variable name which can be set and used dynamically. A
normal variable is set with a statement such as:
for($i = 1; $i <= 20; $i++) {
$myVariable = "encoded" . $i;
echo $$myVariable;
}
Use it this way.
Try this code snippet here
<?php
$encoded1=10;
$encoded2=20;
$encoded3=30;
for($i =1;$i<=3;$i++)
{
echo ${"encoded".$i};
}

php array syntax ${ is confusing me

I create a $values array and then extract the elements into local scope.
$values['status'.$i] = $newStatus[$i];
extract($values);
When I render an html page. I'm using the following
<?php if(${'status'.$i} == 'OUT'){ ?>
but am confused by what the ${ is doing and why $status.$i won't resolve
$status.$i means
take value of $status variable and concatenate it with value of $i variable.
${'status'.$i} means
take value of $i variable, append id to 'status' string and take value of a variable 'status'.$i
Example:
With $i equals '2' and $status equals 'someStatus':
$status.$i evaluated to 'someStatus' . '2', which is 'someStatus2'
${'status'.$i} evaluated to ${'status'.'2'} which is $status2. And if $status2 is defined variable - you will get some value.
I wanted to add to the accepted answer with a suggested alternate way of achieving your goal.
Re-iterating the accepted answer...
Let's assume the following,
$status1 = 'A status';
$status = 'foo';
$i = 1;
$var_name = 'status1';
and then,
echo $status1; // A status
echo $status.$i; // foo1
echo ${'status'.$i}; // A status
echo ${"status$i"}; // A status
echo ${$var_name}; // A status
The string inside the curly brackets is resolved first, effectively resulting in ${'status1'} which is the same as $status1. This is a variable variable.
Read about variable variables - http://php.net/manual/en/language.variables.variable.php
An alternative solution
Multidimensional arrays are probably an easier way to manage your data.
For example, instead of somthing like
$values['status'.$i] = $newStatus[$i];
how about
$values['status'][$i] = $newStatus[$i];
Now we can use the data like,
extract($values);
if($status[$i] == 'OUT'){
// do stuff
}
An alternative solution PLUS
You may even find that you can prepare your status array differently. I'm assuming you're using some sort of loop? If so, these are both equivalent,
for ($i=0; $i<count($newStatus); $i++){
$values['status'][$i] = $newStatus[$i];
}
and,
$values['status'] = $newStatus;
:)

composed variable after Object Operator in PHP

How can I build a composed variable while creating a variable in PHP?
(Sorry I'm not sure how to call the different elements)
This is what I'm trying to do:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->$language_.$i; // problem is here
}
I would like $language_.$i to be equivalent to name_english_1, next loop name_english_2... The same way I built $language
If you want to use an expression in a computed property, you have to put the expression in braces. Also, you need to put the underscore in quotes.
$data = $arraydata->{$language."_".$i};
However, I suggest you redesign your data structure. Instead of having separate name_LANG_i properties, make a single name property whose value is a multi-dimensional array.
$lang = $this->session->userdata('site_lang');
for ($i=1;$i<=3;$i++) {
$data = $arraydata->name[$lang][$i];
// do something with $data
}
Whenever you find yourself using variable variables or variable properties, it's almost always a sign that you should be using an array instead.
First construct the field name and then use it for accessing the field value from the object $arraydata. So your code should be like this:
$language = 'name_'.$this->session->userdata('site_lang');
for ($i = 1; $i <= 3; $i++) {
$var = "{$language}_{$i}";
$data = $arraydata->$var;
// echo $data;
}

PHP session seems not to keep posted form values

Ladies and gents,
I found a very strange behavior which I cannot explain:
Assume that you have
multiple form elements on your page, maybe rendered by php
each form has one input field with an unique name
on the beginning of that page a session will be started
you store every posted input value in the $_SESSION variable
like this:
<?php
session_start();
$_SESSION["Test"] = "Hello";
foreach ($_POST as $name => $value) {
//echo "_POST: " . $name . ":" . $value . "<br>";
$_SESSION[$name] = $value;
//session_commit();
}
for ($i = 0; $i < 10; $i++) {
echo "<form action=\"multiform.php\" method=\"post\">Value for input $i: <input type=\"text\" name=\"input".$i."\"></form>\n";
}
print_r($_SESSION);
?>
If you use the above code, only the "Test" = "Hallo" will persist after the refresh of the page. Regardless which input value has been posted and stored into the session by the foreach, it will be gone after refresh.
Now the interesting part:
If you add a name to the form like this...
echo "<form name=\"form$i\" action=\"multiform.php\" method=\"post\">Value for input $i: <input type=\"text\" name=\"input".$i."\"></form>\n";
...the posted values will be stored then.
But why?
What has the form name to do with the persistence of the $_SESSION?
EDIT: If the input name only contains numbers, the problem seems to arraise:
<input type=\"text\" name=\"$i\">
Thanks for clarifyng this.
Jan
EDIT2:
If the accessor key for the $_SESSION array only contains numbers, php obviously does not persist the values, so something like this, won't be stored:
<?php
session_start();
for ($i = 1; $i < 10; $i++)
{
$_SESSION[$i] = "Hello $i";
}
?>
The confusing part is, if you do a
print_r($_SESSION)
just after the for loop, it will show 1-10 with Hello 1..10...
Though, after refresh it's gone...
The keys in the $_SESSION associative array are subject to the same limitations as regular variable names in PHP, i.e. they cannot start with a number and must start with a letter or underscore.
Found at http://php.net/manual/en/session.examples.basic.php
Could the problem be the integer as a form name as your edit comment suggests? If you serialize a form using PHP you end up with a variable which name is an integer and PHP's variable name cannot be a plain number. If your problem doesn't persist with a naming convention such as <input type=\"text\" name=\"sometext_$i\">, you should stop using plain numbers as a form element name.
It's also a good idea to give the form fields descriptive names. Form field named "1" or "2" doesn't really tell you anything about the containing value.
This is correct; you can not use a numeric-only key in $_SESSION. Trying to do so with error_reporting on highest level and display_errors set to true will yield a notice:
PHP Notice: Unknown: Skipping numeric key 0 in Unknown on line 0
It does store it in the $_SESSION array, but not actually in the session. Although strange behaviour, the notice is descriptive enough. The fix is easy, by the way, just create an array in $_SESSION['numbers'], for example.
<?php
session_start();
for ($i = 1; $i < 10; $i++) {
$_SESSION['numbers'][$i] = "Hello $i";
}
var_dump( $_SESSION['numbers'] );

Categories