Open post

Dynamically Declaring PHP Variables

I faced an interesting problem today. I needed to find a way to dynamically generate a variable name based on how many items found in an array.

I was building a multi-threaded curl request application that could CURL x amount of URLs to y amount of domains by z iterations. My application needed to be flexible enough to take in a variable amount of URLs or domains and then add them to the multi-threader…but how do I accomplish that when PHP variables can’t be declared like:

$x$i = 123; // this throws an error in php

In PHP you can dynamically declare your variables by doing this:

$a = 1;
${'word' . $a} = 'hi'; // sets $word1 = 'hi'

Another way of looking at it:

$urls = [url1, url2, url3, ...];
$domains = [domain1, domain2, domain3, ...];

for ($i=0; $i<=count($urls); $i++) {
    foreach($domains as $domain) {
        ${'path' . $i} = $domain . $urls[$i];

// sets $path1 = domain1/url1;
// sets $path2 = domain2/url1;
// sets $path3 = domain3/url1;
// sets $path4 = domain4/url1;
// and so on...