Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array for values starting with custom selected character

Tags:

arrays

php

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 :)

like image 642
Adam Kiss Avatar asked Apr 05 '11 07:04

Adam Kiss


2 Answers

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);
like image 51
kapa Avatar answered Oct 31 '22 09:10

kapa


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);
like image 37
salathe Avatar answered Oct 31 '22 09:10

salathe