Question

Driving me crazy but here goes:

$cat=2,3,4
$test = print_r(explode(',', $cat), true);
echo ''.$test.'';
foreach ($test as $key => $val) {
echo "$key => $val <br>";
}

What I'm hoping to get:

2
3
4

I'm trying to use a string of numbers obtained from another code to build an array, and then show each value on separate lines. What am I doing wrong?

Was it helpful?

Solution

You shouldn't assign print_r() to $test variable... It's a debugging function for printing purposes..

You should write your code like this..

$cat='2,3,4';
foreach(explode(',',$cat) as $v)
{
    echo $v."<br>";
}

OTHER TIPS

This should be either:

$test = explode(',', $cat);

or:

print_r(explode(',', $cat), true);
<?php

$cat='2,3,4';
$array = explode(',', $cat);
$test = print_r($array, true);
echo ''.$test.'';
foreach ($array as $key => $val) {
echo "$key => $val <br>";
}

$test is string. You need array for foreach statement.

Try with this:

    <?php
$cat = "2,3,4"; // This is a string separated with commas.

    $test = explode(',', $cat); // This assign every number to an array item. The print_r() function is not necesary here.

    foreach ($test as $value) {
        echo $value. "<br />\n";
    }
?>

THIS WILL PRODUCE:

2
3
4

Explanation about your errors:

$cat= '2,3,4'; <- ** Missing quotes **

$test = print_r(explode(',', $cat), true); <- **print_r is not needed here **

echo ''.$test.'';

foreach ($test as $key => $val) { <- Not using it propperly

echo "$key => $val
";

}

You miss ; in $cat variable declaration. Use the following code.

$cat=2,3,4;
$test = explode(',', $cat);
foreach ($test as $key => $val) {
echo $val."<br>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top