PDA

View Full Version : array gone wrong.


Red Blaze
03-27-2006, 07:03 PM
This is the little piece of code I'm trying to get working.


<?php
$priceids = $row_call_albums['priceids'];
$arr = array($priceids);
foreach ($arr as $value) {
$value = $value * 2;
echo $value;
}
?>


In this case, $priceids calls 1, 2, 3.

Now, it does call it, but it doesn't loop. It does 1x2, and stops there. But if I replace "$priceids" with "1, 2, 3", it works just fine. It multiplies 1x2, then 2x2, then 3x2.

The results with $priceids in the array is just "2". But the results for "1, 2, 3" in the array is "246".

Is there a way around this issue? Thanks in advance.

sabret00the
03-27-2006, 07:06 PM
try <?php
$priceids = $row_call_albums['priceids'];
$arr = array($priceids);
print_r($arr);
/*foreach ($arr as $value) {
$value = $value * 2;
echo $value;
}*/
?> if it gives you an array then?

<?php
$priceids = $row_call_albums['priceids'];
$arr = array($priceids);
foreach ($arr as $key => $value)
{
$key = $value * 2;
echo $key;
}
?>

Red Blaze
03-27-2006, 07:12 PM
This is my result when I put
print_r($arr);

Array ( [0] => 1, 2, 3 )

And when I tried $arr as $key => $value, gave me the same result as before. Just plain 2.

sabret00the
03-27-2006, 11:46 PM
the fix is
<?php
$priceids = $row_call_albums['priceids'];
$arr = explode(" ", $priceids);
foreach ($arr as $key => $value)
{
$key = $value * 2;
echo $key;
}
?>

Code Monkey
03-28-2006, 02:03 AM
the fix is
<?php
$priceids = $row_call_albums['priceids'];
$arr = explode(" ", $priceids);
foreach ($arr as $key => $value)
{
$key = $value * 2;
echo $key;
}
?>

You can cut out a line of code by just using this.


$arr = explode(' ', $row_call_albums['priceids']);

No sense adding another variable to memory when it's not needed.

Actually, if the rusults of $row_call_albums['priceids'] has the format of 1, 2, 3 then you should explode it into array with ',' not ' '.

Paul M
03-28-2006, 02:24 AM
Since they are comma seperated the explode should be using a comma, not a space ;

$arr = explode(",", $priceids);