Search code examples
phparraysconditional-statementsfilteringgrouping

Split array into two arrays based on the first character of each element


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)

The first array is the result of a validation function, and since I hate, when a validator returns information about required inputs in a million lines (like: this is required <br><br> that is required...), instead of outputting real messages, I want to output the names of the required and unfilled inputs, to be put into nice one message 'Fields this, that and even that are mandatory'.


Solution

  • 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);