Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.