Jesse Elser Jesse Elser - 1 year ago 104
PHP Question

PHP Variables In File Name

I did a quick Google search and didn't find anything on this so I'm not entirely sure if this is even possible.

Let's say I have a file with the name of

Is it possible to use parts of the file name as variables?

becoming in a php script
$type = "grayscale"
$title = "Waterfall"

Basically I'd like to store variables and values in a filename and extract them if possible.

I know I could use a database for this, but I have reasons for explicitly wanting to try something like this.

Ok so my mind completly drew a blank and I didn't even think about the fact that the file name is nothing more than a string.

With some reminders from some comments I remembered this small detail and came up with the following which works, but doesn't seem to be the best way to do so:


$data = "img_type-grayscale_title-waterfall";
list($fileType,$type, $title) = explode("_",$data);

list($type, $typeValue) = explode("-", $type);
list($title, $titleValue) = explode("-", $title);

echo "Type: " . $typeValue;
echo " ";
echo "Title: " . $titleValue;


Type: grayscale Title: waterfall

It just seems a bit excessive to have to add a new line like
list($title, $titleValue) = explode("-", $title);
for each variable.

Answer Source

I think I would do so with an associative array.


$filename = 'img_type-grayscale_title-waterfall';
$result = Array();

//let's parse the filename with _ as first level separator and - for second level

$firstlevel = explode ('_', $filename);
foreach ($firstlevel as $secondlevels) {
        $keyvalue = explode ('-', $secondlevels);
        //first the special case of the "img" first token which is the file type and has no value
        if (!isset($keyvalue[1])) { // there is for it a key but no value
        else {


echo $result['filetype']; //  "img"
echo ' ; ';
echo $result['type']; // "grayscale"
echo ' ; ';
echo $result['title']; // "waterfall"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download