Skip to content

Instantly share code, notes, and snippets.

@oaass
Last active December 11, 2015 08:59
Show Gist options
  • Save oaass/4577325 to your computer and use it in GitHub Desktop.
Save oaass/4577325 to your computer and use it in GitHub Desktop.
<?php
$required = array('hostname', 'username', 'password', 'database', 'driver');
$config = array(
'password' => 'pass',
'database' => 'mydb',
'charset' => 'utf8',
'port' => '1234'
);
$errors = array_diff($required, array_flip($config));
$last = array_pop($errors);
$errmsg = 'Missing required configurations. No %s or %s has been configured';
var_dump(sprintf($errmsg, implode(', ', $errors), $last));
@oaass
Copy link
Author

oaass commented Jan 20, 2013

What stuff is it you think I should scratch? :)

@flavius
Copy link

flavius commented Jan 20, 2013

@oaass starting with the second comment I said unapplicable stuff to this code. Using $last could become dangerous and the principles I've outlined after the second comment would kick in, only if you use that variable for some "business logic", and not just error string formatting.

For instance, if you would also be doing:

if($last == 80) {
    //assuming that $last is always the port number
}

@oaass
Copy link
Author

oaass commented Jan 20, 2013

@flavius yeah I agree $last can a "dangerous" variable for this. This was just for showing. It also requires for two elements to be missing as well. But it was just to illustrate that this was simpler than array_map. I wasn't actually able to make array_map work in this situation, which was why I looked elsewhere for a solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment