Declare multiple variables in a PHP script to save space

I have a huge form and declare all these variables ...

$MaidenName= $_POST['MaidenName'];
$PhoneHome= $_POST['PhoneHome'];
$SSN= $_POST['SSN'];
$BirthPlace= $_POST['BirthPlace'];
$DOB= $_POST['DOB'];
$Email= $_POST['Email'];
$MaritalStatus= $_POST['MaritalStatus'];  +many more...

I was hoping I could declare them on the same line to save space in the script with a comma, but this will not work ... is there any other way?

+3
source share
4 answers

I wrote this when you chose a different answer, but here anyway:

$item = array('MaidenName', 'PhoneHome', 'SSN', 'BirthPlace', 'DOB', 'Email', 'MaritalStatus');

foreach ($item as $key => $value)
{
    $key = $value;
    echo $key . "\n"; // this line is just for testing
    $_POST['$value'];
}

this is a more professional way to do it.

+1
source

I see that there is an accepted answer, but still I want to share the "inconclusive" way:

extract(array_intersect_key($_POST, array_flip(['a','b','c'])));

This will create $ a, $ b and $ c vars from $ _POST, ignoring all other keys

+1
source

. :

<?php
    $array = array("favfruit"=>"apple","favcar"=>"ford","favgal"=>"sally","favsite"=>"stackoverflow");
    print $array['favfruit'];
?>

:

<?php
    $personaldetails = array("MaidenName"=>$_POST['MaidenName'],"PhoneHome"=>$_POST['PhoneHome'],"SSN"=>$_POST['SSN'],"BirthPlace"=>$_POST['BirthPlace'],"DOB"=>$_POST['DOB'],"Email"=>$_POST['Email'],"MaritalStatus"=>$_POST['MaritalStatus']);
    print $personaldetails['MaidenName']; // This is how you would reference the array later
?>
0

foreach $_POST.

foreach ($_POST as $key => $value){
    $$key = $value; // mention the double $ sign. It wil create variable variable names
}

See http://phpfiddle.org/main/code/m7r-gyw for a working example.

0
source

All Articles