4
\$\begingroup\$

Would it be better to convert the array in the following code to

$langs = array("en", "de", "fr");

and then reusing the values for both $folder and $flag? If so, how then would my foreach (or maybe a while?) loop be written?

<?php
 $langs = array(
 "en/" => "en.png",
 "de/" => "de.png",
 "fr/" => "fr.png"
 );
 $self = $_SERVER['REQUEST_URI'];
 $pattern = "{^.*/}i";
 $links = array();
 foreach ($langs as $folder => $flag) {
 $url = preg_replace($pattern, "$folder", $self);
 $link = "<li><a href=\"../$url\"><img src=\"../img/$flag\"></a></li>";
 array_push($links, $link);
 }
 echo implode($links) . "\n";
?>

I'm trying to "fool proof" the code, by effectively limiting the folder structures and file names that can be used, as I create a basic template of files for quick rolling out of our websites. If you can see any other improvements, that would be much appreciated.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 6, 2014 at 15:14
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can definitely simplify this, as the only part of each element of $langs that changes is the two-letter language code. Something like this would work:

<?php
$langs = array(
 "en",
 "de",
 "fr"
);
$self = $_SERVER['REQUEST_URI'];
$pattern = "{^.*/}i";
$links = array();
foreach ($langs as $code) {
 $url = preg_replace($pattern, "$code/", $self);
 $link = "<li><a href=\"../$url\"><img src=\"../img/$code.png\"></a></li>";
 array_push($links, $link);
}
echo implode($links) . "\n";
?>

You just use a non-associative array and append / or .png where needed; much cleaner.

answered Feb 6, 2014 at 15:52
\$\endgroup\$
1
  • \$\begingroup\$ Thank you. Once you see it written out, you realise it's so simple yet so effective! \$\endgroup\$ Commented Feb 6, 2014 at 17:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.