Php Variable Variables - php

Ive got some generated arrays, and their variable names stored in another array like the following
$array1 = 4x119 array;
$array2 = 4x119 array;
etc ..
$var1= [
"array1",
"array2",
etc...
];
and trying to loop though them like this
foreach ($var1 as $loopitem){
var_dump($$loopitem[3]);
}
How can i make this less ambiguous ?
Currenly im fairly sure its looking for a variable called the contents of $loopitem[3] instead of looking at $arr1[3] as without the [3] the var dump returns correct
Without the [3]
array(4) {
[0]=>
array(119) {
rest of output
With [3]
NULL
Any suggestions ?

You can use ${$loopitem}[3] to make it readable and unambiguous. Actually I'd always use that syntax for variable variables since $$foo is easy to misread as $foo.
However, it would be even better not to use them at all and use an array instead!

Related

$$array[0] returns array name letter and not array value

I would like to use the first value of a dynamically created array but I get the first letter of the array name instead.
$log = "dets_".$id;
$$log = array();
while ($c = mysql_fetch_assoc($cuenta)) { array_push($$log,$c['id'].'::'.$c['fecha']); }
When I print $$log I get something like this:
Array ( [0] => 124::2017-04-07 [1] => 119::2017-04-07 [2] => 118::2017-04-05 )
But when I try to access the first key:
echo $$log[0];
I get "$d" and not "124::2017-04-07". I also tried $log[0] and get "d".
Thank you.
You could access the first element by somewhat tricky expression:
var_dump (${${'log'}}[0]);
http://php.net/manual/en/language.variables.variable.php
A bit of explanation Taken from PHP Manual
In order to use variable variables with arrays, you have to resolve an
ambiguity problem. That is, if you write $$a[1] then the parser needs
to know if you meant to use $a[1] as a variable, or if you wanted $$a
as the variable and then the [1] index from that variable. The syntax
for resolving this ambiguity is: ${$a[1]} for the first case and
${$a}[1] for the second.

Create key => value pair array only if variables are set

I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.
I have created the variables only if the information is present as such:
if(!empty($_POST["user-jobtitle"])){
$idealJobTitle = $_POST["user-jobtitle"]; }
So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.
I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.
I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?
$other_info = array (
"other_info" => array(
if(isset($message)){
"message" => $message
},
if(isset($salaryRange)){
"salary_range" => $salaryRange
},
if(isset($idealJobTitle)){
"ideal_job_title" => $idealJobTitle
}
if(isset($applyFor)){
"ideal_applying_for" => $applyFor
}
)
);
An expected result, if the user has not provided an ideal job title on the form, would be as such:
array(1) {
["other_info"]=>
array(3) {
["message"]=>
string(18) "my message here"
["salary_range"]=>
string(19) "£25k - £30k"
["ideal_applying_for"]=>
string(18) "Cat cuddler"
}
}
As you can see in the above, the ideal_job_title key and value are simply not present.
You should not conditionally declare variables. That's just asking for problems later on.
Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
You can't have nested if statements within an array declaration.
The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:
$other_info = array('other_info' => array_filter($_POST));
Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.
If you name variables as key in the array, you can use compact function. Undefined variable will not be in array
$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");
You can use the below code :
$other_info = array();
if(isset($message)){
$other_info['other_info']["message"] = $message;
}
if(isset($salaryRange)){
$other_info['other_info']["salary_range"] = $salaryRange;
}
if(isset($idealJobTitle)){
$other_info['other_info']["ideal_job_title"] = $idealJobTitle;
}
if(isset($applyFor)){
$other_info['other_info']["ideal_applying_for"] = $applyFor;
}
You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:
$info = array();
// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
$info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
$info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
$info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
$info["ideal_applying_for"] = $_POST["applyFor"];
}
// Voila! Your data is now in $info instead of several variables
// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
"other_info" => $info,
);

Double array elements in php

I have found some code which is really confusing for me. Maybe it's my mistake or I misunderstand. I have seen some code like this:
function my_compare($a, $b) {
if ($a['practice_id']['practice_url'] == $b['practice_id']['practice-url'])
return $a['practice_location_id']['practice-url'] - $b['practice_location_id']['practise_url'];
else
return $a['practice_id']['practice_url'] - $b['practice_id']['practise_url'];
}
I just need to know the use of practice_url and practise_location_id and practice_url .
Are these both embedded in html name or value? Please help me to understand these.
$a is an associative array. "practice_id" and "practice_url" are keys. As usual, the PHP manual has good info: http://us1.php.net/manual/en/language.types.array.php.
it's a "simple" multi-dimensional php array
In php, arrays can contains number, string, object, or an other array.
for example
$a = array('practice_id' => array('practice_url' => 2));
$b = array('practice_id' => array('practice_url' => 1));
echo $a['practice_id']['practice_url']; // display "2"
This code takes two arrays of arrays. As an example:
$a = array(
'practice_id' => array(
'practice_url'=>'some url'
),
'practice_location_id' => array(
'practice-url'='some other url'
)
);
Of course without seeing the code the arrays could be anything.
$a is an array above. $a['practice_id'] refers to the array inside $a with key 'practice_id' (as an aside this is a strangely named key as it would suggest to me that the entry is a string or number rather than an array). Likewise $a['practice_id']['practice_url'] refers to the some url value.
The function is therefore just checking if certain parts of the array are equal and returning based on that. I.e.
return $a['practice_id']['practice_url'] - $b['practice_id']['practise_url'];
Note that the above is the second strange part. Either practice_url is a number and has an oddly named key or it is indeed a url and the return will attempt to convert both to an integer before returning their difference.

Adding key-value in PHP array?

Inside a loop where I'm dealing with variables related to a product and a number of units, I'm trying to add these two to an array:
$pedido = array();
So,
foreach($_POST as $post_key => $post_value){
if ($post_value=="on") {
$nombreProducto = mysql_fetch_assoc($mySQL->query("SELECT nombre from productos WHERE id_producto='$post_key'"));
$cantidad = $_POST[$post_key."Number"];
echo "<h1>".$nombreProducto['nombre']."</h1>"." Cantidad: ".$cantidad." <br><br>";
$pedido["$nombreProducto"] = $cantidad;
}
}
It's right in:
$pedido["$nombreProducto"] = $cantidad;
Where I try to perform the adding, however the output of var_dump is like:
array(1) { ["Array"]=> string(1) "3" }
Not exactly what I wanted neither the format.
Use $pedido[$nombreProducto['nombre']] = $cantidad; instead of $pedido["$nombreProducto"] = $cantidad;
Remove quotes and
$pedido[$nombreProducto['nombre']] = $cantidad;
EDITED
It seems $nombreProducto is an array so you need to indicate the key field, so i changed to use the field "nombre"
If you see your var_dump it's an Array with the key "Array" this is why you are trying to convert the array to string and it return the word "Array"
You shouldn't be putting a variable by itself in quotes. Remove the quotes.
Also, since you were just accessing $nombreProducto['nombre'] on the previous line, it's fairly obvious that that variable is an array. You cannot use an array as a key, only integers and strings are allowed. So use something that identifies it, such as its ID number.
The following makes no sense to do:
$pedido["$nombreProducto"] = $cantidad;
What are you trying to do here? I think what you want to do is this:
$pedido[$nombreProducto['nombre']] = $cantidad;
Also you may want to try to output the array like this:
print_r($pedido);
I recommend you re-write the mysql query so you don't need to loop it. That is for safety and efficiency reasons. I also recommend you use mysqli instead of mysql, because mysql is deprecated and unsafe to use. You don't check if $_POST[$post_key."Number"] is set, at least not in this code. I hope you sanitize/validate the input from $_POST before using it against the database?

Php $_GET issue

foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo "$_GET[$field]";
echo "<br>";
}
print_r($datarray);
This is the output I am getting. I see the data is there in datarray but when
I echo $_GET[$field]
I only get "Array"
But print_r($datarray) prints all the data. Any idea how I pull those values?
OUTPUT
Array (
[0] => Array (
[0] => Grade1
[1] => ln
[2] => North America
[3] => yuiyyu
[4] => iuy
[5] => uiyui
[6] => yui
[7] => uiy
[8] => 0:0:5
)
)
EDIT: When I completed your test, here was the final URL:
http://hofstrateach.org/Roberto/process.php?keys=Grade1&keys=Nathan&keys=North%20America&keys=5&keys=3&keys=no&keys=foo&keys=blat&keys=0%3A0%3A24
This is probably a malformed URL. When you pass duplicate keys in a query, PHP makes them an array. The above URL should probably be something like:
http://hofstrateach.org/Roberto/process.php?grade=Grade1&schoolname=Nathan&region=North%20America&answer[]=5&answer[]=3&answer[]=no&answer[]=foo&answer[]=blat&time=0%3A0%3A24
This will create individual entries for most of the fields, and make $_GET['answer'] be an array of the answers provided by the user.
Bottom line: fix your Flash file.
Use var_export($_GET) to more easily see what kind of array you are getting.
From the output of your script I can see that you have multiple nested arrays. It seems to be something like:
$_GET = array( array( array("Grade1", "ln", "North America", "yuiyyu", "iuy", "uiyui", "yui","uiy","0:0:5")))
so to get those variables out you need something like:
echo $_GET[0][0][0]; // => "Grade1"
calling echo on an array will always output "Array".
print_r (from the PHP manual) prints human-readable information about a variable.
Use <pre> tags before print_r, then you will have a tree printed (or just look at the source. From this point you will have a clear understanding of how your array is and will be able to pull the value you want.
I suggest further reading on $_GET variable and arrays, for a better understanding of its values
Try this:
foreach ($_GET as $field => $label)
{
$datarray[]=$_GET[$field];
echo $_GET[$field]; // you don't really need quotes
echo "With quotes: {$_GET[$field]}"; // but if you want to use them
echo $field; // this is really the same thing as echo $_GET[$field], so
if($label == $_GET[$field]) {
echo "Should always be true<br>";
}
echo "<br>";
}
print_r($datarray);
It's printing just "Array" because when you say
echo "$_GET[$field]";
PHP can't know that you mean $_GET element $field, it sees it as you wanting to print variable $_GET. So, it tries to print it, and of course it's an Array, so that's what you get. Generally, when you want to echo an array element, you'd do it like this:
echo "The foo element of get is: {$_GET['foo']}";
The curly brackets tell PHP that the whole thing is a variable that needs to be interpreted; otherwise it will assume the variable name is $_GET by itself.
In your case though you don't need that, what you need is:
foreach ($_GET as $field => $label)
{
$datarray[] = $label;
}
and if you want to print it, just do
echo $label; // or $_GET[$field], but that's kind of pointless.
The problem was not with your flash file, change it back to how it was; you know it was correct because your $dataarray variable contained all the data. Why do you want to extract data from $_GET into another array anyway?
Perhaps the GET variables are arrays themselves? i.e. http://site.com?var[]=1&var[]=2
It looks like your GET argument is itself an array. It would be helpful to have the input as well as the output.

Categories