0

I'm pulling data from a dozen different text fields into a single multidimensional array, but I would like for a key to only be created if there are elements to add to it. Example:

$colors = array(
  'red'     => $options['red_users'],
  'orange'  => $options['orange_users'],
  'green'   => $options['green_users']
);

Let's say there is no data in the 'orange_users' input field. Other than running a conditional check on each variable, e.g...

if (!$options['orange_users']) {

...how can I efficiently validate that data exists for each input field I'm pulling from?

3
  • foreach( $vbulletin->options as $X){...} Commented Jun 16, 2013 at 3:59
  • "Other than running a conditional check on each variable" - a conditional check on each variable is what you need if, indeed, you want to validate that each variable is not empty. Commented Jun 16, 2013 at 4:06
  • In your example you are basically copying your array, changing the keys. So in this specific case most efficient would be to use just your original array (or put the whole array unchanged in another array if you are joining multiple arrays). Commented Jun 16, 2013 at 4:09

1 Answer 1

2

The easiest way to do this is with a ternary if

  $replacements = array(
    'red'     => isset($vbulletin->options['red_users'])?$vbulletin->options['red_users']:null,
    'orange'  => isset($vbulletin->options['orange_users'])?$vbulletin->options['orange_users']:null,
    'green'   => isset($vbulletin->options['green_users'])?$vbulletin->options['green_users']null
  );

Then to weed out the empty values just use array_filter

  $replacements = array_filter($replacements);
Sign up to request clarification or add additional context in comments.

11 Comments

That's what I was looking for. Thanks. Although, I noticed you said "easiest." Is that meant to imply it's not the most efficient, or that there is a better way?
for one you should use the isset (or empty or array_key_exists) to test or you will get runtime notices in the event that it doesn't exist. and this notation you have will return the value for red if the value for red is not set, so it wouldn't make much sense
the format for the ternary is (expression?true value:false value)
it is probably the most efficient and straight forward way as well to answer your first question.
@jordojuice Cool I didn't know about the truthy part of that returning the value. But in the event of an isset test as the comparison it would return the results of the test instead of that value of the variable in the test.... right?
|

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.