Page 1 of 1

use php array element as variable name

Posted: Wed Oct 07, 2009 1:07 pm
by mattmill30
Hi,

I've manually written out an array, and was hoping to create individual variables for each of the array elements.

Code: Select all

$mandatory_fields = array('company_postcode','company_country','company_telephone','account_email','account_forename','account_surname');
for ($i=0; $i = count($mandatory_fields) -1; $i++) {
    if ($_POST[$mandatory_fields[$i]] = "") {
    $ //i want this variable, if $i were 0, to be $company_postcode
    }
}
 
Is this possible?

Basically, i'm looking for a way of echoing potential errors.
The purpose of the mandatory field element varaible, is i'd echo that variable next to the mandatory html field, if theres no problem, it'll be blank, if there is, the user will see the error.

Does anyone know of a better way of doing this, if its not possible to do what i had hoped?

Thanks,

Matthew Millar

Re: use php array element as variable name

Posted: Thu Oct 08, 2009 4:04 am
by robnet
I'm not sure exactly what you need but take a look at the foreach loop and the code below. If I'm completely off the mark, let me know :)

Code: Select all

$array=array('a' => 'x', 'b' => 'y', 'c' => 'z');
foreach($array as $key => $value){
 ${'var'.$key} = $value; 
}
echo "$vara $varb $varc";

Re: use php array element as variable name

Posted: Thu Oct 08, 2009 6:03 am
by Mark Baker
Just as a note for robnet, look at PHP's extract() function

Code: Select all

$array=array('a' => 'x', 'b' => 'y', 'c' => 'z');
extract($array);
echo "$vara $varb $varc";
 
@mattmill30
extract($_POST);

Re: use php array element as variable name

Posted: Thu Oct 08, 2009 6:22 am
by robnet
Thanks Mark. There's always more to learn :)

Re: use php array element as variable name

Posted: Thu Oct 08, 2009 7:53 am
by Eric!
Mark Baker wrote:Just as a note for robnet, look at PHP's extract() function

Code: Select all

$array=array('a' => 'x', 'b' => 'y', 'c' => 'z');
extract($array);
echo "$vara $varb $varc";
Just to be anal...I think the echo should match the "key" name:

Code: Select all

$array=array('a' => 'x', 'b' => 'y', 'c' => 'z','myName'=>'Eric');
extract($array);
echo "$a $b $c $myName";

Re: use php array element as variable name

Posted: Thu Oct 08, 2009 8:14 am
by Mark Baker
Eric! wrote:Just to be anal...I think the echo should match the "key" name:
Yeah! quote and edit can have its real downside when you forget one line because you were focusing on the others