1

I want to search for '01.' that begins with the number of the array.

Expected output:

1 => string '01.02' (length=5)
2 => string '01.03' (length=5)
3 => string '01.04' (length=5)
32 => string '02.02' (length=5)
33 => string '02.03' (length=5)
34 => string '02.04' (length=5)
35 => string '02.05' (length=5)

My code:

$key = array_search('/^01./', $tomb_datum);
echo $key;
var_dump($key);

These preg match not work.

2
  • 1) array_search doesn't take a regex as argument. 2) Do you want all elements starting with 01 or just the first one? Commented Mar 18, 2016 at 12:10
  • All array number with begin 01. Commented Mar 18, 2016 at 12:17

3 Answers 3

5

There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.

See the below example: FIDDLE

$haystack = array (
  '01.02',
  '01.03',
  '02.05',
  '02.07'
);

$matches  = preg_grep ('/^01/i', $haystack);

print_r ($matches);
Sign up to request clarification or add additional context in comments.

1 Comment

There is another array, I want to be filtered based on the number next to the date
0

If you're looking to filter the array, use array_filter:

$resultArray = array_filter($array, function($elm) {
  if (preg_match('/^01/', $elm)) {
    return true;
  } 
  return false;
});

Hope this helps.

3 Comments

You could just return the preg_match directly w/o the ifs. Also, preg_grep is clearly better suited for this...
There is another array, I want to be filtered based on the number next to the date
Your approach can be interesting if you avoid the regex: function($elm) { return strpos($elm, '01') === 0; }
0

You could use T-Regx library which allows for all sorts of array filters:

pattern('^01.')->forArray($tomb_datum)->filter()

You can also use other methods like:

  • filter() - for regular (sequential) arrays
  • filterAssoc() - for associative arrays (filterAssoc() preserves keys)
  • filterByKeys() - to filter an array by keys, not values

PS: Notice that with T-Regx you don't need /.?/ delimiters!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.