dcdeiv dcdeiv - 2 months ago 8
PHP Question

Dynamically update a php array with a function

I have multiple sitemaps and I would like to merge them all, but before merging them, I need to append a unique variable to all values in all arrays.

// The global variable
define("BASE_URL", "http://domain.com");
$sitemap_full = [ "home" => BASE_URL ];

// One of the arrays
$sitemap_example = [
"foo" => "/bar",
"gnu" => "/lar"
];


Since I have multiple of those arrays, I wanted to create a function that will append the link.

function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
return $sitemap[$title] = BASE_URL . $url;
}
}


And in action in will be:

pushToSitemap($sitemap_example, $sitemap_full);


But this just doesn't work because if I
print_r($sitemap_full);
it will display
Array( "home", "http://domain.com" );
.

What really annoys me is that if in the function I echo them, they will be echoed.

What am I doing wrong?

EDIT

It should display

Array(
"home" => "http://domain.com"m
"foo" => "http://domain.com/bar",
"gnu" => "http://domain.com/lar
);

Answer

Your problem seems lie inside your foreach function:

function pushToSitemap($initial_sitemap, $sitemap) {
    foreach ($initial_sitemap as $title => $url) {
      return $sitemap[$title] = BASE_URL . $url;
    }
}

You are returning just a single item, what's more, the formatting is off.

Instead,

function pushToSitemap($initial_sitemap, $sitemap) {
    foreach ($initial_sitemap as $title => $url) {
      $sitemap[$title] = BASE_URL . $url;
    }
    return $sitemap;
}

$sitemap_full = pushToSitemap($sitemap_example, $sitemap_full);
Comments