Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Match on a Array Key

I need to get the stock values out of this array:

Array ( 
[stock0] => 1
[stockdate0] => 
[stock1] => 3 
[stockdate1] => apple 
[stock2] => 2 [
stockdate2] => 
) 

I need to pattern match on this array, where the array key = "stock" + 1 wildcard character. I have tried using the array filter function to get every other value on the PHP manual but the empty values seem to throw it out. I tried alot of different things I found but nothing is working.

Can this be done?

like image 694
Oliver Avatar asked Oct 20 '09 16:10

Oliver


3 Answers

<?php

$foo = 
array ( 
'stock0' => 1,
'stockdate0' => 1,
'stock1' => 3,
'stockdate1' => 2,
);

$keys = array_keys( $foo );
foreach ( $keys as $key ) {
    if ( preg_match( '/stock.$/', $key ) ) {
    var_dump( $key );
    }
}

I'm hoping I interpreted correctly and you wanted 'stock', 1 wildcard character thats not a newline, then end of string.

like image 132
meder omuraliev Avatar answered Nov 04 '22 20:11

meder omuraliev


You should store those as:

Array(
  [0] => Array(
    stock => 1,
    stockdate => ...
  ),
  [1] => Array(
    stock => 3,
    stockdate => apple
  ),
  ...
)
like image 26
Jeff Ober Avatar answered Nov 04 '22 19:11

Jeff Ober


Since PHP 5.6.0 the flag option has been added to array_filter. This allows you to filter based on the array keys rather than its values:

array_filter($items, function ($key) {
  return preg_match('/^stock\d$/', $key);
}, ARRAY_FILTER_USE_KEY);
like image 4
Peleg Avatar answered Nov 04 '22 20:11

Peleg