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?
<?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.
You should store those as:
Array(
[0] => Array(
stock => 1,
stockdate => ...
),
[1] => Array(
stock => 3,
stockdate => apple
),
...
)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With