ConorReidd ConorReidd - 2 months ago 7
PHP Question

PHP - Stop need to create hundreds of variables

I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.

I'll obviously shorten this down but my current script is:

$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];

if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }

$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);

array_count_values(array_merge($a0,$a1,$a2));


I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated

Answer

You should be able to produce the same output that you get from array_count_values with a nested foreach loop.

foreach ($tags['items'] as $x) {                       // loop over the list of items
    foreach ($x['snippet']['tags'] as $tag) {          // loop over the tags from each item
        $tag = strtolower($tag);
        if (!isset($counts[$tag])) $counts[$tag] = 0;
        $counts[$tag]++;                               // increment the tag count
    }
}
Comments