Jump to content

Dynamic Creation of Variables


sKunKbad

Recommended Posts

I'd like to check a bunch of post variables, all of which will either be yes or null values, and then create variables for the ones that have yes values. For instance, if $_POST['apple'] has a value of yes, I want my script to create a variable named $apple, and give it a yes value. The script needs to create the variable by using the name of the $fruits array member or post var, but I just can't figure it out.

 

Here is what I have so far:

<?php
$fruits = array("apple","orange");
foreach( $fruits as $fruit ){
if(isset($_POST["$fruit"])){
	if($_POST["$fruit"] == 'yes'){
		echo "$fruit";
                          //so here is where I would want the variable to be created from the post var or $fruits array member.
	}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/93563-dynamic-creation-of-variables/
Share on other sites

Why not just use arrays?

 

<?php
$fruits = array("apple","orange");
foreach( $fruits as $fruit ){



if(isset($_POST["$fruit"])){





if($_POST["$fruit"] == 'yes'){







        $$fruit = "yes";
                          //so here is where I would want the variable to be created from the post var or $fruits array member.
}
}
?>

 

That should solve the way you requested (not sure someone may need to correct me on it.

 

Here is a preferred and more efficient way to do it.

 

<?php
$fruits = array("apple","orange");
foreach( $fruits as $fruit ){



if(isset($_POST["$fruit"])){





if($_POST["$fruit"] == 'yes'){







echo "$fruit";
                          //so here is where I would want the variable to be created from the post var or $fruits array member.
$fruit_arr[$fruit] = "yes";
}
}

echo $fruit_arr['apple']; // would print yes if apple was listed with the value of "yes"
?>

 

 

 

EDIT:

 

Note those extra spaces are from using [ php ] and not [ code ]  (I really wish they would remove the [ php ] tag and keep it as [ code ] to prevent that mis-understanding.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.