Dynamic Variables and Arrays in PHP - php

I have a variable that is dynamic and updates once every day from a cache file, but when I wish to display the variable it pulls nothing although my cache file has the information stored.
This is an example of what I am trying to do...
$var1 = "1"; // Dynamic info that is previously pulled from the cache file.
$var2 = array (
"0" => "2",
"1" => "3" );
Now I want to display the content of a certain part of the array...
echo "Test ".$var2['$var1'];
This is meant to output: Test 3
And if $var1 was a 0 it would output: Test 2
I have tried this many other ways, including changing the ' to ", or not even including them, it either displays a PHP error or it displays nothing apart from the "Test" text.
EDIT#1:
Ok, so this is to explain what I am doing a little bit better.
First I pull from a file and replace anything that comes with it that I don't need..
$myFile = "http://someserver.com/afile.txt";
$lines = file($myFile);
$ngender = preg_replace('/Gender=/', '', $lines[3]);
Now, I know that the above code works fine, its when I get to the array that I have problems..
$ngen = array (
1 => "Male",
2 => "Female"
);
Then I use $ngen[$ngender]; to store it into the xml file, but it don't store anything. This is actually I am trying to do before I store it into the xml file.

It should be:
echo "Test ".$var2[$var1];
$var1 is a variable so it should no be in ''.

A few things:
Not all PHP arrays are associative. The following is valid and more efficient:
$var2 = array(1 => "Male", 2 => "Female");
Variable names don't need to be stringified inside of statements. Your specific problem is caused because '$var2' would evaluate to the literal string $var2, while "$var2" would evaluate to "1".
So the correct code:
$var1 = "1"; // Dynamic info that is previously pulled from the cache file.
$var2 = array(1 => "Male", 2 => "Female");
echo "Test ".$var2[$var1];
The error you've posted on the other answer's comment suggest that $var1 isn't what you think it is. Make sure.

Related

MySQL JSON strings with PHP. fixing commas

I'm creating this JSON thingy and I need to remove the last comma from it. (yes I know I could do a simple way instead of making the json myself, but I need it to be like this {"1":0,"2":4,"3":1.5}) So how can I do it? (And yes I have a working way in the code but it doesent display it like I need it.)
<?php
require 'dbConnect.script.php';
$query="SELECT * FROM `trash`";
if($is_query_run=mysql_query($query)){
print "{";
while($query_execute=$query_execute=mysql_fetch_assoc($is_query_run)){
echo '<tr><td>"'.$query_execute['id'].'"</td>:<td>'.$query_execute['weight'].',</td></tr>';
//$rows = array();
//$rows[] = $query_execute;
//print json_encode($rows);
}
print "}";
}
else{
echo "query notexecuted";
}
?>
In your example, you can simply create an array:
$array = ["1" => 0, "2" => 4, "3" => 1.5];
$json = json_encode($array);
Since this array doesn't start with a zero (which indexed arrays does), this would give you your desired result.
If you want to start with a zero, and still get an object back:
$array = ["0" => 2, "1" => 0, "2" => 4, "3" => 1.5];
you can use the option JSON_FORCE_OBJECT as a second parameter, like this:
$array = ["0" => 2, "1" => 0, "2" => 4, "3" => 1.5];
$json = json_encode($array, JSON_FORCE_OBJECT);
This will give you:
{
"0": 2,
"1": 0,
"2": 4,
"3": 1.5
}
Read more here: http://php.net/manual/en/function.json-encode.php
It's seldom a good idea to build your own encoders/decoders for things like this. It usually gets quite complicated pretty quick, and you will spend most of your time straighten out bugs and get stuck on edge cases. It's better to read up on the native functions. They have been tried and tested for years, and are often much better in regards of performance.
Whilst I concur json_encode is the nicest solution for producing JSON. To produce a nice comma separated output you could use the implode function.
Set-up your elements in an array, so for example:
$data = array('"1":0', '"2":4', '"3":1.5');
Then use implode like this
$output = implode(',', $data);
Which will give you an output of the data elements in the array as a comma separated list
if($is_query_run=mysql_query($query)){ //Here you execute the query
while($query_execute=$query_execute=mysql_fetch_assoc($is_query_run)){ //Here you get one row from execution result
$rows = array(); //You create array into $rows, what was in $rows before will be wiped
$rows[] = $query_execute; // You insert one row you just fetch from result to $rows
print json_encode($rows); // You encode $rows (which always has only one element as you wipe it every iteration)
}
}
So, create array before loop, and encode that array after loop, adding elements to array inside a loop is ok.
-Mr_KoKa #LinusTechTips.com

In PHP, how can I convert an Array (dictionary) inside String variable to Array structure?

I was looking for in Stack some solution to convert a string variable to an Array. The String variable contents this:
$myvar = 'array("a" => array("b1" => 1, "b2" => "something"), "c" => array("d1" => 1))';
I want to convert as:
$myarray = array(
"a" => array (
"b1" => 1,
"b2" => "something"
),
"c" => array("d1" => 1)
);
I was using json_decode after to convert my huge string to json, I used implode too ...
Using eval, I recieve next error:
Parse error: syntax error, unexpected '<' in tabletocreate.php(51) : eval()'d code on line 1
I used print_r($myvar);
The idea it is I have an model inside a file model.php it is only a dictionary, I read this file inside a string and after to convert again an array, I do it because I need to generate a new database from this data, and I have the model for each catalog I need products, offer, ... obiously each model will be different but with the same structure of array, I wrote in the example
SOLUTION
faintsignal resolved the solution in my case: eval("\$myarray = " . $myvar . ';');
Use eval() http://www.php.net/manual/en/function.eval.php
$myarray = eval($myvar)
But don't do this if you're getting the $myvar from outside your script. Also, there are much better methods to serialize and unserialize data in PHP. For instance see http://www.php.net/manual/en/function.serialize.php
If you're reading a .php file directly you have to deal with <?php and ?>. You can pre-parse the file before passing it to eval(). If your file is as simple as:
<?php (php_declarations_and_stuff ?>
You can just remove <?php and ?>, and the eval() the file.
Another option may be just use include against the file. See http://www.php.net/manual/en/function.include.php. In this case include will eval the file in the global scope. Also see that if your included file uses return, you can just retrieve this value directly (See Example #5 in the include reference):
return.php
<?php return 'Ok'; ?>
myfile.php
$val = include('return.php');
print $val;
Will print "Ok".
eval() will accomplish what you need, but as another poster here advided in his answer, you must use this function with great caution.
$myvar = 'array("a" => array("b1" => 1, "b2" => "something"), "c" => array("d1" => 1))';
eval("\$myarray = " . $myvar . ';');
var_dump($myarray);
outputs
array(2) {
["a"]=>
array(2) {
["b1"]=>
int(1)
["b2"]=>
string(9) "something"
}
["c"]=>
array(1) {
["d1"]=>
int(1)
}
}
Someone commented that eval is deprecated but I cannot find any info to support this. However, its use is discouraged, so you might consider it as a last resort when existing PHP functionality will not accomplish your task.

Php Variable Variables

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!

Modify array values in a file

I have a php file with some arrays in it. I want to modify one of these arrays and write it back to the file. For e.g. say file test.php has contents -
<?php
$arr1 = array("a"=>"b", "c" =>"d");
$arr2 = array("a2" => "b2", "c2" => "d2");
i want to change $arr1 so that test.php now looks like -
<?php
$arr1 = array("a"=>"b", "c" =>"d", "e"=>"f");
$arr2 = array("a2" => "b2", "c2" => "d2");
I do not know what arrays are present in the file beforehand.
Edit: i am not adding any variables to the array, only another key value pair. The problem is that the array is part of a file with more arrays in it about which I won't always be aware. I can achieve this if there was only one array in the file, but want to know if it is possible to do this with multiple arrays.
You could introduce another "global" array
$arr = array('arr1' => array("a"=>"b", "c" =>"d"), 'arr2' =>("a2" => "b2", "c2" => "d2"));
and serialize it
$serArr = serialize($arr);
//write to file here
When you read the file, just unserialize its content so you have the "global" array with it's sub-arrays, modify the values you need, serialize it and write it back.
Keep in mind that this can be a huge performance issue when you write big arrays.
If you are within a function (i.e. not in global scope) get_defined_vars() might be a good bet. You'd just need to include the file in a closed scope and return it's keys to get all variable names in the file.
<?php
$arr1 = array("a"=>"b", "c" =>"d");
$newarr=array("d"=>"f");
$arr1+=$newarr;
it's has been 5 years, but i want to give simple way that work for me.

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