Question

I have an array that looks like this:

$elm = 'a,b,c';

I need the values of the array so I use explode to get to them:

$q = explode(",",$elm);

I then would like to echo every single item into a span, so I make an array:

$arr = array();
foreach($html->find($q[0]) as $a) {
$arr[] = $a->outertext;
}

$arr2 = array();
foreach($html->find($q[1]) as $b) {
$arr2[] = $b->outertext;
}

$arr3 = array();
foreach($html->find($q[2]) as $c) {
$arr3[] = $c->outertext;
}

And then finally I output like this:

echo "<ul>";

for($i=0; $i<sizeof($arr + $arr2 + $arr3); $i++)
{
    echo "<li>";
       echo "<span>".$arr[$i]."</span>";
       echo "<span>".$arr2[$i]."</span>";
       echo "<span>".$arr3[$i]."</span>";
    echo "</li>";
}

echo "</ul>";

The problem is that I have to write all the items ($q[0] + $q[1] + $q[2]) and the corresponding span (<span>".$arr[$i]."</span>) This is a problem because in reality I don't know what and how long the first array ($elm) is. Therefore I don't want to 'physically' write down all the span elements but rather create them on the fly depending on the array $elm. I tried many things but I can't figure it out.

Was it helpful?

Solution

The basic issue here is that you don't know how many elements $elm will contain. foreach is the best choice here, as it doesn't require the length of the array to loop through it.

Use a nested foreach loop to store all the outertexts in an array:

foreach (explode(",", $elm) as $elem) {
    foreach ($html->find($elem) as $a) {
        $arr[$elem][] = $a->outertext;
    }
} 

$arr[$elem][] is the important bit here. On each iteration of the outer loop, the value of $elem will be a, b and c. On each iteration of the inner loop, it will create a new index in the array: $arr['a'], $arr['b'] and $arr['c'] and add the outertext values to the respective index.

Once you've stored all the required values in the array, it's only a matter of looping through it. Since we have a multi-dimensional array here, you will need to use a nested loop again:

echo "<ul>";    

foreach ($arr as $sub) {
    echo "<li>";
    foreach ($sub as $span) {
        echo "<span>".$span."</span>";
    }
    echo "</li>";
}    

echo "</ul>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top