2

Im am so lost. Can anyone explain how i can shorten this code. I have hundreds of these! I submit a form with input value. Whenever i dont fill in a value, i get an error. So i made these isset blocks to prevent returning the error. But i seem so unefficient! Please help...thanks

if(isset($_POST['input74'])){
$value74 = $_POST['input74'];
}else{
$value74 = "";#default value
}

if(isset($_POST['input75'])){
$value75 = $_POST['input75'];
}else{
$value75 = "";#default value
}

if(isset($_POST['input76'])){
$value76 = $_POST['input76'];
}else{
$value76 = "";#default value
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
  • One option: `$value74 = isset($_POST['input74']) ? $_POST['input74'] : "";`. You could loop and replace the number with a variable. – FirstOne Nov 16 '15 at 22:22
  • 3
    If you find yourself numbering inputs like this, then you should probably use an array instead.... and then you can loop over it in PHP rather than explicitly having to name each element – Mark Baker Nov 16 '15 at 22:22
  • Use the ternary operators like @FirstOne suggested to get the variable assignments on a single line. However, you really should follow the advice from Mark Baker – iam-decoder Nov 16 '15 at 22:27
  • 2
    Please update your question with a sample from your form. It will be easier to provide an alternative or an answer to your question – Alex Andrei Nov 16 '15 at 22:31
  • 1
    Also, it would help to know how are you going to use the variables from the `$_POST` – Alex Andrei Nov 16 '15 at 22:37
  • A brief synopsis of the bigger picture of what you are trying to do here would be helpful. What you are doing in the code in your question really seems more indicative of a design error. – Don't Panic Nov 16 '15 at 23:12

7 Answers7

1

you could wrap the isset in a function like this

function myIsset(&$variable, $default = "")
{
    if(isset($variable))
    {
        return $variable;
    }
    else
    {
        return $default;
    }
}

then you just call it like $value74 = myIsset($_POST['input74']);

the second argument defaults to an empty string so if you want to set the default value you can supply it or change what the default is in the function header if they will just all be the same. bellow is a screen shot showing the code working

test

while yes you are still going to have one line per $_POST at least you exchnge 5 lines of code with 1 line of code and the function above. you can possibly reduce this to a loop like how i explain in this answer however without seeing the form and confirming any pattern i can't give any code examples for that since what you have shown could just be a coincidence

Community
  • 1
  • 1
Memor-X
  • 2,870
  • 6
  • 33
  • 57
  • Change it to `myIsset(&$variable, ...` – rjdown Nov 16 '15 at 22:39
  • @AbraCadaver that is incorrect. i tried it with not just the OP's `$_POST` variables but also this line of code `$hello = "dood"; var_dump(myIsset($hello));`. commenting out the `$hello` line and it shows that it will return whatever i specified `$default` to when commented out and when it isn't it'll return the exact same value passed. adding `&$variable` gave the exact same resaults – Memor-X Nov 16 '15 at 22:40
  • 2
    @Memor-X turn on error reporting and you will see why your code is incorrect. Pass the variable by reference instead, to avoid the undefined variable warning, which is really the point of using isset in the first place. There is a version of this function in the comments section of the isset manual page http://php.net/manual/en/function.isset.php#95557 – rjdown Nov 16 '15 at 22:44
  • @rjdown ahhh that might be why. i tend to have those turned off – Memor-X Nov 16 '15 at 22:46
  • @downvoter if your downvote was about how i originally had `$variable` instead of `&$variable` then you can remove your downvote as that has been fixed. otherwise please explain what is wrong – Memor-X Nov 16 '15 at 23:04
  • Not my downvote, though I did explain what was wrong, and I see you fixed it. Have an upvote :) There was another comment above mine that has since been deleted, saying that the variable would always be set in the function... it was wrong though. – rjdown Nov 16 '15 at 23:04
1

PHP 7 has a new operator to address this specific situation: the null coalesce operator (??) replaces this:

$foo = isset($foo) ? $foo : $bar

With this:

$foo = $foo ?? $bar;
miken32
  • 42,008
  • 16
  • 111
  • 154
0

PHP has support for arrays in forms. You can name your form fields with indexes, e.g. <input type="text" name="input[74]" ... />. Then in PHP, you can access those with a for or foreach loop, because they will be available as an array (i.e. you will have $_POST["input"][74]). You could thus write something like:

$values = $_POST["input"];
for ($i = 0; $i < MAX_INPUTS; $i++) {
  if (!isset($values[$i])) {
    $values[$i] = "";  // default value
  }
}

If for some reason you can't change the HTML side, you could still use a loop to dynamically create the field names and copy the data to an array on the PHP side, something like:

$value = array();
for ($i = 0; $i < MAX_INPUTS; $i++) {
  $name = sprintf("input%d", $i);
  if (isset($_POST[$name])) {
    $value[$i] = $_POST[$name];
  } else {
    $value[$i] = "";  // default
  }
}

In both proposed solutions, you only have some lines of code instead of dozens of repetitions of almost the same lines. In both examples, I assumes that your fields start with input0 and that there is a total of MAX_INPUTS fields. If not all fields exist (e.g. you only have input1, intput2, input74 and input75), you can create an array with the fields numbers:

$field_list = array(1,2,74,75);

And then use that to check your data (here the example with arrays in HTML field names):

$values = $_POST["input"];
foreach ($field_list as $num) {
  if (!isset($values[$num])) {
    $values[$num] = "";  // default value
  }
}
Ale
  • 1,727
  • 14
  • 26
  • your example won't work, as using the name field will turn all of the contents into strings. `name="input[74]"` will actually come out as `$_POST["input"]["74"]`, NOT `$_POST["input"][74]`. not only that, `HTML` actually holds the support for arrays in forms creating a querystring that php can decipher. But so can Java or JavaScript – iam-decoder Nov 16 '15 at 22:28
  • Sorry @iam-decoder: That is not correct. Integer keys will be integer keys in PHP. – AbraCadaver Nov 16 '15 at 22:41
  • Indeed, I just tried... although string indexes wouldn't hurt anyway because of dynamic typing. – Ale Nov 16 '15 at 22:42
  • weird, does this differ on IIS servers? because the string casting was the answer to a question here on SO not too long ago – iam-decoder Nov 16 '15 at 22:44
  • it is clearly stated in the PHP manual that any string index to an array that is a valid integer will be used as such... see this answer: http://stackoverflow.com/a/26119646/1931985 -- @iam-decoder, do you have a link to the IIS-related answer for string casting? I'm curious to see more about this... – Ale Nov 16 '15 at 22:49
  • is there a way to view all the posts I commented on? I believe I didn't submit an answer on that post – iam-decoder Nov 16 '15 at 23:00
  • @iam-decoder in your profile go to the activity tab, go to "all actions" tab and select "comments". it'll appear there unless the comment or answer has been deleted – Memor-X Nov 16 '15 at 23:02
  • @Ale here it is, i see now that It's because it was converted to a JSON object rather than an array which caused my confusion: [Create multidimensional array only with html](http://stackoverflow.com/questions/33657080/create-multidimensional-array-only-with-html#comment55089283_33657080) – iam-decoder Nov 17 '15 at 00:14
0

Use ternaries to shorten the code:

$value74 = isset($_POST['input74']) ? $_POST['input74'] : 'Default value';
$value75 = isset($_POST['input75']) ? $_POST['input75'] : 'Default value';
$value76 = isset($_POST['input76']) ? $_POST['input76'] : 'Default value';

Or you could loop through $_POST array as well, but some filtering/validation must be done. Quick idea:

if(!empty($_POST)) {
    $i = 0;
    $arr = array();
    foreach($_POST as $input) {
        $arr[$i] = $input;
        $i++;
    }
}

$arr would then produce an array like

Array
(
    [74] => 'value74'
    [75] => 'value75'
    [76] => 'value76'
)
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
KEK
  • 473
  • 3
  • 15
0

You could use array_merge.

You would set up your default array with all the default input values provided.

$aryDefault = ['input74'=>'', 'input75'=>'',...]

Then array_merge this with your post array, and it will fill in all the missing values. NOTE: Order is important check out the docs.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Use array_merge($aryDefault, $_POST) so that $_POST overwrites the defaults.

Also, you can use variable variables so you can do this in a loop. If all your variable are named after your array keys, like in your example.

Full Code:

$aryDefault = ['input74'=>'', 'input75'=>'',...];
$aryFinal = array_merge($aryDefaults, $_POST);
foreach( $aryFinal as $key=>$value){
  $$key = $value;
}

You could even generate $aryDefault with a loop, if its super big.

$aryDefault = array();
for(i=0;i<=100;i++){
  $aryDefault["input$i"] = "";
}
Dan
  • 10,614
  • 5
  • 24
  • 35
0

If I understand you correctly seeing that you want to set a variable to post or otherwise default value you can do it following the below structure:

$variable = isset($_POST['name']) ? $_POST['name] : "defaultvalue";

That will set the variable of it exists otherwise set the default value specified. I hope this helps.

0

You can create a simple function to encapsulate the code before PHP 7:

function post($key, $default = null){
    return isset ($_POST[$key])?$_POST[$key]:$default;
}

Since PHP 7 (using the null coalescing operator (??)):

function post($key, $default = null){
    return $_POST[$key] ?? $default;
}

or better whithout function just simple (as mentioned above)

$value74 = $_POST['input74'] ?? ''; #default value
$value75 = $_POST['input75'] ?? ''; #default value
$value76 = $_POST['input76'] ?? ''; #default value
shaedrich
  • 5,457
  • 3
  • 26
  • 42
Steve
  • 20,703
  • 5
  • 41
  • 67