$_POST better writing quality - php

I have this code :
if(isset($_POST['prenom2'])){
$t['prenom2'] = $_POST['prenom2'];
}else{
$t['prenom2'] = '';
}
if(isset($_POST['nom2'])){
$t['nom2'] = $_POST['nom2'];
}else{
$t['nom2'] = '';
}
if(isset($_POST['prenom3'])){
$t['prenom3'] = $_POST['prenom3'];
}else{
$t['prenom3'] = '';
}
etc (there are 5 or 6 fields I need to test).
There must be a better way of doing this, like if a given index of POST isn't set, that index is...
Thanks

You can use foreach.
$indexes = array('prenom2', 'nom2', ...);
$t = array();
foreach ($indexes as $i) {
$t[$i] = isset($_POST[$i]) ? $_POST[$i] : '';
}
print_r($t);

If you don't want to use if..else.. condition then you can use ternary : operator as
$t['prenom2'] = (isset($_POST['prenom2'])) ? $_POST['prenom2'] : '';
$t['nom2'] = (isset($_POST['nom2'])) ? $_POST['nom2'] : '';

Basically the same as the answer from Matei but moved in a function to reduce duplicate code.
Parameter $t is your final array and $key is a string representing the array index. The final $t array is also returned so there is no need for passing a reference.
function setT($t, $key)
{
$t[$key] = isset($_POST[$key]) ? $_POST[$key] : '';
return $t;
}
$t = setT($t, 'prenom1');
$t = setT($t, 'prenom2');
$t = setT($t, 'prenom3');

Based on your real problem, you may choose one of these:
for($i=1; $i<6; $i++){
$t['prenom'.$i] = (isset($_POST['prenom'.$i])) ? $_POST['prenom'.$i] : '';
$t['nom'.$i] = (isset($_POST['nom'.$i])) ? $_POST['nom'.$i] : '';
}
or
$indexes = array('prenom2'=>'', 'nom2'=>'', ...);
$t = array_merge($indexes,$_POST);

Related

Best way to check if lots of variables contain a string and if so change it?

I have lots of variables that I need to check to see if it is equal to "None". If a variable is equal to "None" I would like to change it to = "-";
What's the best practice way of doing this without having a separate IF function for each variable?
//Variables
$profileEthnicity = h($result["profile_ethnicity"]);
$profileHeight = h($result["profile_height"]);
$profileBuild = h($result["profile_build"]);
$profileEyeColor = h($result["profile_eye_color"]);
$profileHairColor = h($result["profile_hair_color"]);
$profileTattoos = h($result["profile_tattoos"]);
$profilePiercings = h($result["profile_piercings"]);
//Example
if($profileEthnicity == "None") { $profileEthnicity = "-"; }
Since the values are in an array you can do this:
foreach($result AS $key => $val) {
('None' == $val) ? $result[$key] = '-' : $result[$key] = $val;
}

htmlspecialchar to multiple variables

I was wondering if there's a simpler way of doing this
$admsquarecmail = #$_POST['squarecmail'];
$admsquarecmail = htmlspecialchars($admsquarecmail, ENT_COMPAT);
$admsquarecsubject = #$_POST['squarecsubject'];
$admsquarecsubject = htmlspecialchars($admsquarecsubject, ENT_COMPAT);
$admsquarectymessage = #$_POST['squarectymessage'];
$admsquarectymessage = htmlspecialchars($admsquarectymessage, ENT_COMPAT);
$admsquarecontagain = #$_POST['squarecontagain'];
$admsquarecontagain = htmlspecialchars($admsquarecontagain, ENT_COMPAT);
The idea is not to type
htmlspecialchars($var, ENT_COMPAT);
every time a variable is added.
Method 1:
You may apply htmlspecialchars to all elements of $_POST with array_map:
$arr = array_map("htmlspecialchars", $_POST, array_fill(0, sizeof($_POST), ENT_COMPAT));
Then:
$admsquarecmail = isset($arr['squarecmail']) ? $arr['squarecmail'] : "";
$admsquarecsubject = isset($arr['squarecsubject']) ? $arr['squarecsubject'] : "";
$admsquarectymessage = isset($arr['squarectymessage']) ? $arr['squarectymessage'] : "";
...and so on.
Method 2:
You may apply htmlspecialchars to the elements of $_POST one by one. In this method you don’t need an array apart from $_POST itself:
$admsquarecmail = isset($_POST['squarecmail']) ? htmlspecialchars($_POST['squarecmail'], ENT_COMPAT) : "";
$admsquarecsubject = isset($_POST['squarecsubject']) ? htmlspecialchars($_POST['squarecsubject'], ENT_COMPAT) : "";
$admsquarectymessage = isset($_POST['squarectymessage']) ? htmlspecialchars($_POST['squarectymessage'], ENT_COMPAT) : "";
...and so on.
Method 3:
You may create a small function like the following:
function obtain_POST_value($key){
if(array_key_exists($key, $_POST)) return htmlspecialchars($_POST[$key], ENT_COMPAT);
return "";
}
Then:
$admsquarecmail = obtain_POST_value('squarecmail');
$admsquarecsubject = obtain_POST_value('squarecsubject');
$admsquarectymessage = obtain_POST_value('squarectymessage');
...and so on.

Parsing empty XML elements in PHP

PHP newbie here. I'm parsing a long XML file, setting each tag to a variable. If the element's tag is empty, I want to assign it the value "N/A"
I'm wondering if there's a more concise way to do this than my current approach:
$elements = array()
$propertyOwner = $report->PropertyProfile->PrimaryOwnerName[0];
array[] = $propertyOwner;
$propertyAddress = $report->PropertyProfile->SiteAddress[0];
array[] = $propertyAddress;
...
for($i=0; $i<count($elements); $i++) {
if (array[i] === '') {
array[i] = 'N/A');
}
}
The way the code was written originally (without $s in front of each variable) you'd probably be getting errors all day. Hope this helps simplify:
$array[] = '';
$elements = array();
$propertyOwner = $report->PropertyProfile->PrimaryOwnerName[0];
$elements[] = $propertyOwner;
$propertyAddress = $report->PropertyProfile->SiteAddress[0];
$elements[] = $propertyAddress;
//...
// IF THEN ELSE
$array[] = !empty($elements) ? $elements : 'N/A';

Undefined indexes in PHP. Generic solution required

I have been searching Stack Overflow and the rest of the web, and I am starting to believe that there is no generic solution for undefined indexes.
I have a massive PHP application with several form and at the end of the script I call all the form's inputs and put them together to display a summary of all the inputs.
echo $_POST['FirstName'];
echo $_POST['MiddleName'];
echo $_POST['LastName'];
I know how to check each occurence like
if ( !isset($_POST['MiddleName']) ) { $_POST['MiddleName'] = '' }
Is there a way to automatically capture all undefined indexes and then set them to 0 or null?
It's as simple as looping trough an array of all indexes that may be defined:
$indexes_that_MUST_be_defined_but_can_be_empty = array(
'FirstName',
* * *
'LastName'
);
foreach($indexes_that_MUST_be_defined_but_can_be_empty as $index) {
if( ! isset($_POST[$index])) {
$_POST[$index] = NULL;
}
}
Or even you can preset different defaults like this:
$indexes_that_MUST_be_defined_but_can_be_empty = array(
'FirstName' => NULL,
* * *
'LastName' => NULL
);
$_POST = array_merge($indexes_that_MUST_be_defined_but_can_be_empty, $_POST);
If you really just want to suppress the warnings, you can use # like in:
echo htmlspecialchars(#$_POST['any_index']);
but I really don't recommend this.
EDIT:
Here's one more possible solution. A "magical" function that uses a pointer:
function null_if_not_defined(&$variable) {
return isset($variable) ? $variable : NULL;
}
// Usage:
echo htmlspecialchars(null_if_not_defined($_POST['any_index']));
You can do it using below function.
function setNullValue($arr)
{
$newarr = array();
foreach($arr as $key => $ar)
{
if($ar == "")
{
$newarr[$key] = 0;
}
else
{
$newarr[$key] = $ar;
}
}
return $newarr;
}
print_r(setNullValue($_POST));
If you want to show only those indexes with assigned values, you could do something like this:
foreach ($_POST as $index => $value) {
echo "{$index}: {$value}<br/>";
}
you can also create a simple function for this purpose:
$p = function($item) {
return isset($_POST[$item]) ? $_POST[$item] : null;
};
Now you can use it as such :
echo $p('MiddleName');
foreach($_POST as $key=>$value) {
if($value == "") $_POST[$key] = 0;
}

change empty array element to a value

i have an array like this
Array ([0]=>'some values'[1]=>'')
I want to change the empty elemnt of an array to a value of 5
how can I do that
thanks
5.3 version
$arr = array_map(function($n) { return !empty($n) ? $n : 5; }, $arr);
If you know at which position it is, just do:
$array[1] = 5;
If not, loop through it and check with === for value and type equality:
foreach($array as &$element) { //get element as a reference so we can change it
if($element === '') { // check for value AND type
$element = 5;
}
}
You can use array_map for this:
function emptyToFive($value) {
return empty($value) ? 5 : $value;
}
$arr = array_map(emptyToFive, $arr);
As of PHP 5.3, you can do:
$func = function($value) {
return empty($value) ? 5 : $value;
};
$arr = array_map($func, $arr);
EDIT: If empty does not fit your requirements, you should perhaps change the condition to $value === '' as per #Felix's suggestion.
This $array[1] = 5;

Categories