I have a quickie :)
I have null-based array consisting of string values:
array
0 => string 'Message 1' (length=9)
1 => string '%company' (length=8)
2 => string 'Message 2' (length=9)
3 => string '%name' (length=5)
I need to pick all values starting with %
and ideally put them into another array.
array
0 => string 'Message 1' (length=9)
1 => string 'Message 2' (length=9)
array
0 => string '%company' (length=8)
1 => string '%name' (length=5)
Thank you!
For anyone interested, the first array is result of validation function, and since I hate, when validator return information about required inputs in million lines (like: this is required <br><br>
that is required...), instead of outputting real messages, I output names of required and unfilled inputs, to be put into nice one message 'Fields this, that and even that are mandatory' :)
Miniedit: will be grateful even for links for questions with answers on stackoverflow :)
PHP >5.3, below that you need to use create_function().
This solution first filters the original array, and gets the items that begin with %
. Then array_diff() is used to get the array with the remaining values.
$array_percent = array_filter($orig_array, function ($v) {
return substr($v, 0, 1) === '%';
});
$array_others = array_diff($orig_array, $array_percent);
Apologies for resurrecting the question, but simple filtering like this is super simple with preg_grep()
.
$subject = array('Message 1', '%company', 'Message 2', '%name');
$percents = preg_grep('/^%/', $subject);
$others = preg_grep('/^%/', $subject, PREG_GREP_INVERT);
var_dump($percents, $others);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With