Tech

En till Good Old Blogs webbplats

Ensuring that values are in an array

I’ve run across situations where I want to ensure that some values exist in a non-associative array (without getting duplicates). The way I’ve usually solved it is:

if (!in_array('nid', $fields)) {
  $fields[] = 'nid';
}
if (!in_array('title', $fields)) {
  $fields[] = 'title';
}

This is kind of ugly, and the more values you want to add the uglier it becomes, so it evolved to:

$ensure = array('nid','title');
foreach ($ensure as $f) {
  if (!in_array($f, $fields)) {
    $fields[] = $f;
  }
}

This is great if you have a known array of values that always should exists. But if you have third party code that could have requirements for certain fields to be there, or logic that’s more spread out that determines the fields that needs to be ensured, this is the way I’ve settled for:

$fields = array_fill_keys($fields, TRUE);

// Add a required field
$fields['nid'] = TRUE;

// Add a set of required fields
$fields += array_fill_keys(array('title', 'created'), TRUE);

// Add another set of required fields
$fields += array('modified' => TRUE, 'teaser' => TRUE);

$fields = array_keys($fields, $ensure);

This way we get away with not using loops or conditions by first turning the values into keys in a associative array, modifying them, and then turning the keys into an array again. I guess this is a matter of personal preferences, and this last approach might have the drawback that it’s not immediately obvious what’s going on for the uninitiated. The other two approaches are more readable.

Kommentarer

 

Här var det tomt!

Ingen har skrivit en kommentar på den här artikeln. Bli den första!