I have an array of output from a database. I am wondering what the cleanest way to filter the values is
example array
Array
(
[0] => Array
(
[title] => title 1
[cat_title] => Drawings
[sec_title] => Portfolio
)
[1] => Array
(
[title] => title 2
[cat_title] => Paintings
[sec_title] => Portfolio
)
[2] => Array
(
[title] => title 3
[cat_title] => Drawings
[sec_title] => Portfolio
)
)
As an example what would be the cleanest way to make all of the cat_title to uppercase and all of the sec_title’s to htmlspecialchars?
I was thinking if i sorted the array improperly that I could use the array map function. like this
improper array
Array
(
[title] => Array
(
[0] => title 1
[1] => title 2
[2] => title 3
)
[cat_title] => Array
(
[0] => Drawings
[1] => Paintings
[2] => Drawings
)
)
Then I could do something handy like:
array_map('strtoupper', $array['cat_title']);
and make all of the cat_titles uppercase in one go. Something like that would sure beat this, which is what I have going on now.
$count = count($array);
for($i=0; $i < $count; $i++) {
//filter list output
if (isset($array[$i]['cat_title'])) {
$array[$i]['cat_title'] = strtoupper($array[$i]['cat_title']);
}
}
Do you guys know of anyway I could callback functions on numbered array’s a little bit more elegantly then above? Hopefully without sorting the array incorrectly? something like array_map or array_walk?
You can do this with
array_walk, it would be something like:However, functions like
htmlspecialcharsare really only intended for the very last moment when you’re actually sending content to the browser. Before then, you want to work with the raw text and just have<?=htmlspecialchars($var)?>in your template/view file. Otherwise you can end up with encoding problems if you, for example, send that encoded data to a database, then retrieve it and runhtmlspecialcharsagain.UPDATE: Here’s the code I used to test this; it works fine for me. I’m on PHP 5.2 but there isn’t any difference in the function from version 4+.
Outputs: