Home > Back-end >  How to echo just few names of a list, in a clean way
How to echo just few names of a list, in a clean way

Time:11-06

I'm using the following code to list the first 7 names of a long list, for each post. The problem is when a certain post contains a list of names inferior to 7, for each missing name til 7, it automatically prints a comma ','

So when names are 7 or more, it correctly shows: "name1, name2, name3, name4, name5, name6, name7" While, if for example it contains just 3 names, it will print: "name1, name2, name3,,,,"

Is there anyway to add something in the code to exclude printing commas in case of names minor to 7?

<?php
$value = get_post_meta($post->ID, 'list_of_names', true);
$value_array = explode(',', $value);
$hrefs = []; 
for($i = 0; $i < 7; $i  )
{
    $remove_space = str_replace(' ', '-', $value_array[$i]);
    $url = esc_url('myblogurl' . $remove_space);
    if ('' !== $url)
    {
        $display = esc_html($value_array[$i]);
        $hrefs[] = "<a href='$url'>$display</a>";
    }
}
echo implode(",", $hrefs);
?>

I've been trying to add elseif($i < 6) { echo ','; before the end, but it reported me a system error syntax :(

Any advice?

CodePudding user response:

Limit your loop to the size of your $value_array, also maintaining the limit of 7.

for ($i = 0, $count = count($value_array); $i < 7 && $i < $count; $i  )

Another way of coding the same idea:

for ($i = 0, $min = min(7, count($value_array)); $i < $min; $i  )

CodePudding user response:

You have the 'values' in an array, so you could use array functions.

<?php

$values = get_post_meta($post->ID, 'list_of_names', true);
$value_array = explode(',', $values);
$hrefs = []; 
foreach (array_slice($value_array,0,7) as $value)
{
    $remove_space = str_replace(' ', '-', $value);
    $url = esc_url('myblogurl' . $remove_space);
    if ('' !== $url)
    {
        $display = esc_html($value);
        $hrefs[] = "<a href='$url'>$display</a>";
    }
}
echo implode(",", $hrefs);

?>

See: array_slice()

I would advice to use something other than value as a variable name, if you want others to understand what your code is about.

  • Related