Since your logos and urls exist in pairs, you can use a single loop over the logos and access the urls via the shared index.
Code: (Demo)
foreach ($jsonPartenaires['logo'] as $i => $logo) {
$html = sprintf('<img src="%s">', $logo);
if ($jsonPartenaires['url_partenaire'][$i]) {
$html = sprintf(
'<a href="%s">%s</a>',
$jsonPartenaires['url_partenaire'][$i],
$html
);
}
echo $html . "<br>";
}
Output: (tabbed and spaced for readability)
<img src="images/website_logo_1.png">
<br>
<a href="https://www.url_website_2.fr">
<img src="images/website_logo_2.png">
</a>
<br>
<img src="images/website_logo_3.png">
<br>
Using printf()
or sprintf()
(the silent version), enables you to bind variables to a string without the noise of string concatenation or interpolation. If you ever want to call a string function on a variable (to prepare the strings, you can just wrap the parameters containing variables in the desired function(s).
I'll admit that in my own project, I'd probably use functional syntax. This allows you to cleanly join the html elements with <br>
with no trailing <br>
.
Code: (Demo)
echo implode(
"<br>",
array_map(
function($logo, $url) {
$html = sprintf('<img src="%s">', $logo);
if ($url) {
$html = sprintf('<a href="%s">%s</a>', $url, $html);
}
return $html;
},
$jsonPartenaires['logo'],
$jsonPartenaires['url_partenaire']
)
);