Page 1 of 1
preg_grep - empty array() returned - help
Posted: Mon Jul 17, 2006 6:11 am
by bogdan
Hi,
I have this array:
Code: Select all
$albacore = array(
[a] => apple
[b] => banana
[{k}] => lemon
[c] => squid
[d] => pear
)
I want to look into the array, get the elements with [{k}], print them out.
Code: Select all
$results = preg_grep("/\{k\}/",$albacore);
print"<pre>";
print_r ($results);
print"</pre>";
Unfortunately for me, this prints:
Array
(
)
Regards, B
Re: preg_grep - empty array() returned - help
Posted: Mon Jul 17, 2006 6:15 am
by Benjamin
Why not...
Code: Select all
$albacore = array(
[a] => apple
[b] => banana
[k] => lemon
[c] => squid
[d] => pear
)
Posted: Mon Jul 17, 2006 6:19 am
by bogdan
{k} is a template tag in a list of params somwehere, which I am not supposed to alter in any way.
I just have this array of params => values in the end, From which I want to extract the params that have not been set, e.g. they have the tag {k} instead of a set value (something like that).
Posted: Mon Jul 17, 2006 6:19 am
by Chris Corbyn
Oh wow I never knew such a function existed

That could make some of my scripts more efficient
preg_grep() seems to look for array *values* not keys.
Posted: Mon Jul 17, 2006 6:21 am
by Chris Corbyn
To followup, the poor man's preg_grep_keys() would be something like:
Code: Select all
function preg_grep_keys($pattern, $input)
{
$ret = array();
foreach ($input as $k => $v)
{
if (preg_match($pattern, $k)) $ret[$k] = $v;
}
return $ret;
}
Posted: Mon Jul 17, 2006 6:22 am
by bogdan
d11wtq wrote:Oh wow I never knew such a function existed

That could make some of my scripts more efficient
preg_grep() seems to look for array *values* not keys.
Thanks, that cleared a few things. Seems I have to find another way.
Posted: Mon Jul 17, 2006 6:23 am
by JayBird
What about
array_keys()
Also, i presume in the array, you will on have one key that is called {k} otherwise they would be overwritten!?
Posted: Mon Jul 17, 2006 6:47 am
by bogdan
There may be more that are not over written

, keys: white{k}, blue{k}....
I am inclined to look one level above and get them before they are made array keys
Thanks for the array_keys() - I seem to be able to locate the exact position of a set key.