Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare multiple variables in php script to save space

I have a huge form and am declaring 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 maybe declare them on the same line just to save space in the script with maybe a comma but that wont work ... is there another way?

like image 228
Todd Vance Avatar asked Feb 25 '26 02:02

Todd Vance


2 Answers

I was writing this as you were selecting the other answer, but here it is 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'];
}

it's a more professional way of doing it.

like image 87
l'L'l Avatar answered Feb 26 '26 15:02

l'L'l


I see there is an accepted answer, but still want to share a "foreachless" way:

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

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

like image 40
Maximus Avatar answered Feb 26 '26 16:02

Maximus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!