0

I would like to append a string to the values of a nested associative array in PHP.

The following is my array

$styles = array(
    'Screen' => array(
        "master.css",
        "jquery-jvectormap-1.0.css"),
    'handheld' => array("mobile.css") 
     );

Looping over it to change it in the following way fails.

foreach($media as $medium => $filename)
foreach($filenames as &$filename)
    $filename = "/styles/".$filename;

Prefixing $medium with & just causes a syntax error.

This also fails.

function prepend($prefix,$string)
{
return $prefix.$string;
}

foreach($media as &$medium)
  $medium = array_map(prepend("/styles"),$medium); 

What is the simplest way to prefix "/styles/" to those css filenames given this data structure?

3 Answers 3

2

Try this:

$styles = array(
    'Screen' => array(
        "master.css",
        "jquery-jvectormap-1.0.css"),
    'handheld' => array("mobile.css") 
     );

foreach($styles as $k=>$v){
    foreach($v as $a=>$b){
        $styles[$k][$a] = '/styles/'.$b;
    }
}

print_r($styles);
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

foreach($styles as $medium => &$filenames) {
  foreach($filenames as &$filename) {
    $filename = "/styles/".$filename;
  }
}

Some tips:

  • Use braces to structure your nested code. This will give you (and php) a better understanding of what is you meant
  • Use Indenting. This will give you a better overview.
  • Name the Iterating-Variable using the singular of the Array-Variable (ie. foreach($apples as $apple)). This will give you an extra hint with which variable you're dealing with.

Good Luck!

1 Comment

Ah, my error with & was in prepending it to the key (here, medium) and not the value (here, filenames). Thanks for pointing that out.
0
foreach($media as $medium => $filenames) {
    foreach($filenames as $key => $filename) {
        $media[$medium][$key] = "/styles/" . $filename;
    }
}

1 Comment

Won't this modify a copy of $filename?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.