How do I create variables based on an array? PHP - php

I'm quite confused in how would I be able to create variable based on an array's values, my code is:
$a = array("red","black","white","green","blue");
for($i=0;$i>5;$i++)
{
$$a[$i] = '0.00';
}
echo $red;
I was under the impression that emulating a statement that says $red = '0.00'; would run properly but alas, it says undefined variable red.

use this:
for($i=0;$i<5;$i++)
you got error in loop, you have used '>' sign, so loop doesn't work, actually... :)

It's only your assignation that is wrong.
Use a foreach loop to make it easier, and it will work :
$a = array("red","black","white","green","blue");
foreach ($a as $val) {
$$val = '0.00';
}
echo $red;
Output :
0.00

Related

PHP: var_dump while loop

I was trying to create a loop for all the variables on a page to display in one while loop. I couldn't seem to get the variable to output. Here is the code I tried that made the most sense to me:
<?php
$varone = true;
$vartwo = 47;
$varthree = "A little string";
$vars = get_define_vars();
while($loop = $vars){
echo "variable ".$vars;
var_dump($vars;)
}
?>
It would crash one browser and the other it would stay blank. The reason I tried the code this way is because I thought of how I would word a mysql loop and I thought it would work in a similar way. Sorry if this is a newb question.
You should use something like a foreach() loop...
foreach ($vars as $name => $var){
echo "variable ".$name."=";
var_dump($var);
}
Alternatively, I think it might be easier to use an array for this.
$new_array[] = true;
$new_array[] = 47;
$new_array[] = "A little string";
$a=0;
while($new_array[$a]){
echo "variable ".$a." = ";
var_dump($new_array[$a]);
$a++;
}
The reason I tried the code this way is because I thought of how I
would word a mysql loop and I thought it would work in a similar way.
Though I would go with foreach you can use your current code with list and each as many use to fetch from MySQL:
while(list($key, $val) = each($vars)){
echo "variable $key";
var_dump($val); //var_dump($vars;) PARSE ERROR check ;
}
However each is deprecated:
Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on
this function is highly discouraged.

Automatization of a conditional function through the use of an array to test postdata variables

I have some problems to make the following automatization:
I get from a form a lot of variables such as $a and $b.
I would like to automatize a conditional test depending on the variables I obtain.
$test = array('a','b');
for($i=0;$i<sizeof($test);$i++)
For the 1st variable a, the working code is:
if ( $postdata->a !=${$test[$i]}){echo "different";} else {echo "same";}
For the 2nd variable b, the working code is:
if ( $postdata->b !=${$test[$i]}){echo "different";} else {echo "same";}
I would like to automatize it thanks to the array like this:
if ( $postdata->$test[$i] !=${$test[$i]}){echo "different";} else {echo "same";}
but $postdata->$test[$i] doesn't work, even echo $test[$i] gives 'a' and 'b'.
I tried several "writing" but I couldn't solve it.
Thank you for your help.
Instead of making your code too complex with $test[$i] and for loop instead use foreach. Hope this will work fine.
Try this code snippet here contains sample input
<?php
ini_set('display_errors', 1);
$test=array('a','b');
foreach($test as $i => $value)
{
if ($postdata->{$value} != ${$value})
{
echo "different";
}
else
{
echo "same";
}
}

undefined variable and undefined index php errors

I've been given the task to remove undefined variable and undefined index errors, which i know how to
$value = isset($_POST['value']) ? $_POST['value'] : '';
The problem is this is way too time consuming, I predict over 2000 variables, $_GET, $_POST hasn't been set. So is there a regular expression i can use to set these variables quickly?
How do i do regex to change this $category = $_GET['c'] to this
$category = isset($_GET['c']) ? $_GET['c'] : ''?
And how do i do regex to change if($page or $category or $profile) to this
if(isset($page) or isset($category) or isset($profile))?
This is the best method i can think of by using regex find & replace in Notepad++. I assume over 2000 PHP variable/index undefined errors. How do i solve this without turning off errors?
you should not use regex because it's kind of heavy :)
if i'm understanding your question right, you can do this like this,
with this approach, it does not matter how many parameters contains POST or GET, you simply filter them through foreach loop and getting clean arrays with parameters, also you can make it a function that returning array.and then you just need to check if_array_key_exests() and do your things.
$_POST = ["user"=>"1", "num"=>2];
$_GET = ["user" => '', "num"=>1];
//function method
function filter($array)
{
$arr = array();
foreach ($array as $key => $val) {
if (!empty($val)) {
$arr[$key] = $val;
}
}
return $arr;
}
without function
$post = array();
foreach ($_POST as $key => $val) {
if (!empty($val)) {
$post[$key] = $val;
}
}
$get = array();
foreach ($_GET as $key => $val) {
if (!empty($val)) {
$get[$key] = $val;
}
}
For your first problem, replacing something like
(\$\w+)\s*=\s*\$_GET\[['"]?(\w+)['"]?\]\s*;
by
$1 = isset($_GET['$2']) ? $_GET['$2'] : '';
should work.
Regarding the second, I don't know if this is possible with a variable number of variables. This one works for 3 variables, replace
if\s*\(\s*\s*(\$\w+)\s+or\s+(\$\w+)\s+or\s+(\$\w+)\s*\)
by
if (isset($1) or isset($2) or isset($3))
You can add another \s+or\s+(\$\w+) before the last \s* in the search, and add another or isset($4) in the replacement for 4 variables etc.
I recommend you to replace them one by one instead of replacing all at once ;-)
Also note that if ($a) is not the same as if (isset($a)). Consider something like this:
// query string is a=0
$a = $_GET['a'];
if ($a) // will be false
if (isset($a)) // will be true
if (!empty($a)) // will be false
So, perhaps you want to use !empty() instead of isset(). This should work without notices, too.
resove first issue:
define a function like:
function global_get($key){
return isset($_GET[$key])?$_GET[$key]:'';
}
then use sed(linux tool) to replace all parts like this(it will modify all the $_GET[.*] of php extension files in your project,so be careful to use this):
find /yourproject -name "*.php" -exec sed -i "s/\$_GET\[\([^]]*\)\]/global_get(\1)/" \;
you may modify this command to apply your own demand.
The second issue could be harmful if you use the regex expression because it is hard to make a role rule.so I recommend you to replace manually.

PHP Cannot display content variable inside foreach loop when combine two different variable array

I have an multiple variable like this and i want to combine two variable in foreach loop:
$foo = array(4, 9, 2);
$variables_4 = array("c");
$variables_9 = array("b");
$variables_2 = array("a");
foreach($foo as $a=>$b) {
foreach($variables_{$b} as $k=>$v) {
echo $v;
}
}
After i run above code it display error "Message: Undefined variable: variables_"
Is anyone know how to solve this problem?
You can use Variable variables to get the job done, but in this case it is kind of ugly.
A cleaner way to do this is by using nested arrays:
$foo = array(4=>array("c"),
9=>array("b"),
2=>array("a"));
foreach($foo as $a=>$b) {
foreach($b as $k=>$v) {
echo $v;
}
}
Then you won't have to create a lot of variables like $variables_9.
You should try to use eval(), for example:
foreach(eval('$variable_'.$b) as $k=>$v)...
I would highly suggest another route (this is a poor structure). But anyways...
Try concatenating into a string and then use that
$var = 'variables_' . $b;
foreach($$var as $k=>$v) {
echo $v;
}
This is a syntax error.
You need to concatenate the strings within the brackets:
${'variables'.$b}
look at this post for more info.

lost var in php

I am fairly new to PHP and Yii, and the problem that I am not nor as the question in google, so the only thing I can think of is to ask the question to this list that I have solved many problems.
The issue is as follows: in the code that I attached, I read several records that I keep in array and after the process.
Well, if you look at the debug entries in foreach in he first, all goes well and the variable $items is loaded, but when I get to the second debug $items variable has the correct number of elements, but the elements are empty : count ($items) = 2 but $items[0] and $items[1] are null
$idiomas=CListaMidiomas::model()->findAll();
$items=array();
$nombre=array();
$a=0;
foreach ($idiomas as $idioma){
$nombre[$a]=$idioma->sIdioma;
$items[$a]=TblCategoriastexto::model()->findAll(
array('condition'=>'id='.$data->id.' AND idIdioma='.$idioma->id_idioma));
echo "<br>---AAAAAAAAAAA--".$a."-----------<br>";
CVarDumper::dump($items); //in this moment is correct
if (empty($items[$a]) ||$items[$a]==null ){ // not enter because $items have content
$items[$a]=new TblCategoriastexto();
$items[$a]->idIdioma=$idioma->id_idioma;
}
$a++;
}
echo ">>>>>>>>>>>>>>>".count($items) ; //<<<<<<<<<<present 2
CVarDumper::dump($items); // but in this moment t0 2 are null
for ($a=0;$a<count($items) ;$a++){
echo "<b>".CHtml::encode($nombre[$a]).":</b>";
$out="";
$item=$items[$a];
echo "<br>-----".$a."-----------<br>";
CVarDumper::dump($items[$a]);<<<<<<<<<<<<<<<<<<<<<<<<null
for ($b=1;$b<=20;$b++){
$campo="tc".$b;
$out.=$items[$a]->$campo . ",";<<<<<<<<<<<<<<<<error
}
echo CHtml::encode($out);
echo"<br>";
}
This line: if (empty($items[$a]) ||$items[$a]=null ){ will always assign $items[$a] to null.
To compare values, use the comparison (for equality) operator, == instead of the assignment operator =.
Try changing this line:
if(isset($items[$a]->$campo)) {
$out.=$items[$a]->$campo . ",";
}

Categories