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?
Advertisement
Answer
array_filter does not have access to the key and therefore is not the right tool for your job.
I belive what you’re looking to do is this:
$stocks = Array ( "stock0" => 1, "stockdate0" => '', "stock1" => 3, "stockdate1" => 'apple', "stock2" => 2, "stockdate2" => '' ); $stockList = array(); //Your list of "stocks" indexed by the number found at the end of "stock" foreach ($stocks as $stockKey => $stock) { sscanf($stockKey,"stock%d", &stockId); // scan into a formatted string and return values passed by reference if ($stockId !== false) $stockList[$stockId] = $stock; }
Now $stockList looks like this:
Array ( [0] => 1 [1] => 3 [2] => 2 )
You may need to fuss with it a bit, but I think this is what you are asking for.
HOWEVER, you really should be following Jeff Ober’s advice if you have the option to do so.