Unifx Unifx - 1 month ago 11
PHP Question

Best practices for php arrays, foreach and if statements

So I am just learning best practices now and everybody has an opinion and I just want to find a nice clean way of coding which is not .... bad?

I have written the below. It works, No error outputs however I have a feeling this is terrible practice. this is in a Wordpress template.

<?php
$config['social-links'] = [
'facebook' => 'https://www.facebook.com/usernamehere',
'instagram' => 'https://www.instagram.com/usernamehere/',
'twitter' => null,
'youtube' => null
];


and in the template

<ul class="social-nav inline-blocks">
<?php
global $config;
$dir = get_template_directory_uri();
foreach($config['social-links'] as $key => $value) if($value)
echo "
<li class='$key inlineBlock'>
<a class='animate' target='_blank' href='$value'>
<span class='inner'>
<img class='injectSvg' data-src='$dir/images/social-icons/icon-$key.svg' alt='$key'>
</span>
</a>
</li>
";
?>
</ul><!--END Social-nav-->


I have a feeling because I have left them open this is terrible? I know the below works and is correct but I dislike brackets...

foreach($config['social-links'] as $key => $value) {
if($value) {

}
}


I just ended up going with the below...

<ul class="socialNav inlineBlocks">
<?php
global $config;
foreach($config['social-links'] as $key => $value) {
if($value) {
echo '
<li class="'. $key .' inlineBlock">
<a class="animate" target="_blank" href="'. $value .'">
<span class="inner">
<img class="injectSvg" data-src="'. get_template_directory_uri() .'/images/social-icons/icon-'. $key .'.svg" alt="'. $key .'">
</span>
</a>
</li>
';
}
} ?>
</ul><!--END SocialNav-->

Answer

It is terrible practice. If you don't have access to a templating engine (i.e. Twig), then using shorthand/templating PHP like below is the path you should be looking at:

<?php foreach($config['social-links'] as $key => $value): ?>
    <?php if($value): ?>
        <li class="<?php echo $key; ?>" inlineBlock">
             <a class="animate" target="_blank" href="<?php echo $value; ?>">
                <span class="inner">
                    <img class="injectSvg" data-src="<?php echo get_template_directory_uri() .'/images/social-icons/icon-'. $key; ?>.svg" alt="<?php echo $key; ?>">
                </span>
            </a>
        </li>
    <?php endif; ?>
<?php endforeach; ?>

This is commonly known as Alternative Syntax and is the way to go.