0

I have a number of items of data. Sometimes the var is not created/set, sometimes it is. This is because the var data comes from a form with optional fields.

I have created the variables only if the information is present as such:

if(!empty($_POST["user-jobtitle"])){
    $idealJobTitle = $_POST["user-jobtitle"];   }

So if the field user-jobtitle is not filled in, then $idealJobTitle is not created.

I now wish to create an array with a key for each value. But I only want to add to the array if that variable exists. Otherwise, I just want to omit it.

I have written code below which I know is wrong but follows the sort of logic I am after. What is the correct way to do this? Do I really have to run through nested if statements checking if the var exists and only then pushing to the array?

$other_info = array (
    "other_info"  => array(
        if(isset($message)){
            "message" => $message
        },
        if(isset($salaryRange)){
            "salary_range" => $salaryRange
            },
        if(isset($idealJobTitle)){
            "ideal_job_title" => $idealJobTitle
        }
        if(isset($applyFor)){
            "ideal_applying_for" => $applyFor
        }
    )
);

An expected result, if the user has not provided an ideal job title on the form, would be as such:

array(1) {
  ["other_info"]=>
  array(3) {
    ["message"]=>
    string(18) "my message here"
    ["salary_range"]=>
    string(19) "£25k - £30k"
    ["ideal_applying_for"]=>
    string(18) "Cat cuddler"
  }
}

As you can see in the above, the ideal_job_title key and value are simply not present.

8
  • 1
    Are you sure you are not trying to re-create the $_POST array? If you are then just use the $_POST array, or take a copy of it if you like to use twice as much memory as you need Commented Aug 27, 2015 at 11:45
  • @Burki it's completely syntactically incorrect. Commented Aug 27, 2015 at 11:46
  • I should have looked closer before asking that, right? sorry. Commented Aug 27, 2015 at 11:50
  • A ternary operator would work well. No need for nested arrays. Commented Aug 27, 2015 at 11:52
  • 1
    @Fred-ii- You can't conditionally declare keys with a ternary. The best you could do is [] + ($foo ? ['bar' => 'baz'] : []), which, really... please don't. Commented Aug 27, 2015 at 12:03

4 Answers 4

4
  1. You should not conditionally declare variables. That's just asking for problems later on.
  2. Unpacking values from one array into a variable and then conditionally packing them back into an array is needlessly complex. Keep your data in an array and move it around in one "package".
  3. You can't have nested if statements within an array declaration.

The most useful way to handle this would be to use names in your form that you're also going to use later on in your $other_info array. Translating between various variable and key names throughout your code is just terribly confusing, pointless and needlessly requires a ton of additional code. In other words, why does the same piece of information need to be called user-jobtitle and $idealJobTitle and ideal_job_title in different contexts? If you'd keep it consistent, you could simply filter empty values and be done with it:

$other_info = array('other_info' => array_filter($_POST));

Yup, array_filter gets rid of empty elements without individual if statements. You can further use array_intersect_key and similar functions to further filter out keys.

Sign up to request clarification or add additional context in comments.

2 Comments

I think array_filter will be most useful in this case only if other_info not need to contain specific values. :)
Well, again, you can use a bunch of array functions to slice and dice and filter arrays without unpacking every individual value into individual variables. That approach is, honestly, insane.
2

If you name variables as key in the array, you can use compact function. Undefined variable will not be in array

$ar = compact("message", "salaryRange", "idealJobTitle", "applyFor");

3 Comments

What about the empty keys?
Compact does not include undefined variable
This has worked really well and been the lightest way to do this, thanks!
0

You can use the below code :

$other_info = array();

      if(isset($message)){
        $other_info['other_info']["message"] = $message;
      }
      if(isset($salaryRange)){
        $other_info['other_info']["salary_range"] = $salaryRange;
        }
      if(isset($idealJobTitle)){
        $other_info['other_info']["ideal_job_title"] =  $idealJobTitle;
        }
      if(isset($applyFor)){
        $other_info['other_info']["ideal_applying_for"] = $applyFor;
      }

Comments

0

You already have a code that works and puts the values in variables. Create an empty array and put the data directly in the array under various keys instead of individual variables:

$info = array();

// Analyze the input, put the values in $info at the correct keys
if (! empty($_POST["message"])) {
    $info["message"] = $_POST["message"];
};
if (! empty($_POST["salaryRange"])) {
    $info["salary_range"] = $_POST["salaryRange"];
};
if (! empty($_POST["idealJobTitle"])) {
    $info["ideal_job_title"] = $_POST["idealJobTitle"];
}
if (! empty($_POST["applyFor"])) {
    $info["ideal_applying_for"] = $_POST["applyFor"];
}

// Voila! Your data is now in $info instead of several variables

// If you want to get the structure you described in the non-working code you can do:
$other_info = array(
    "other_info" => $info,
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.