How to turn an array of values into another indexed array?

77 views Asked by At

this is a follow up to another question which I was instructed to split up. I have different set of columns and their values some which have values, some which don't. For example:

$vCountries ['country1'] = "Value of country1";
$vCountries ['country2'] = "Value of country2";
$vCountries ['country3'] = "";
$vCountries ['country4'] = "Value of country4";
$vCountries ['country5'] = "";

...through to

$vCountries ['country50'] = "Value of country50";

I would like to generate the following code example (only when it contains a value):

<th id="country1">Value of country1</th>
<th id="country2">Value of country2</th>
<th id="country4">Value of country4</th>

...

Since all country ID's are generically named with only an index to differ them, I would like these headings to be generated dynamically.

Someone has suggested the following code:

for ($i = 1; $i <= 50; ++$i) {
$vCountries['country' . $i] = "Value of country " . $i;}

But firstly, I don't understand how it is working and how I can parse it to the code at the top because for now it only prints array array array etc. and the "Value of country .$i" is not generic and indexed, it is an actual value different for each country, so I would still have to list it manually, no?

Any ideas?

Thanks

3

There are 3 answers

2
Surreal Dreams On

This will do it.

foreach($vCountries as $id => $value)
{
    if($value)
    {
        echo "<th id=\"$id\">$value</th>";
    }
}

This outputs only entries with values. Each id is output as the <th> id, and each value is displayed inside the <th> tag.

1
Dalmas On

This generates the code you want :

foreach ($vCountries as $key => $value)
{
    if (strlen($value) > 0)
        echo "<th id=\"$key\">$value</th>";
}
1
aorcsik On

If your goal is to generate the said HTML code from the array, which is already defined, then this may be a solution for you:

// Loop the array
foreach ($vCountries as $key => $value) {
    // If value is not empty
    if (!empty($value)) {
        // display the line
        echo '<th id="'.$key.'">'.$value.'</th>'."\n";
    }
}