MetaldroiD
MetaldroiD

Reputation: 436

PHP : Getting each value from the array and calculate

I have these values in the array=Array ( [0] => 3 [1] => 2 [2] => 10 [3] => 5 )

How do i get each value separately from the array and perform the below calculation?

$j=$q*100/$ytot;

And this is what i've tried so far, which isnt giving the correct value :

$resul=mysql_query("select * from post_bet where bet_id = '$id'")or die(mysql_error());
if(mysql_num_rows($resul)>0)
{
    while($row=mysql_fetch_assoc($resul))
    {
        $y_uid=$row['yes_userid'];          
        $y_uamt=$row['yes_useramount'];
        $n_uid=$row['no_userid'];
        $n_uamt=$row['no_useramount'];
        $ytot=$row['yes_total'];
        $ntot=$row['no_total'];
        $hhh=explode(',',$row['yes_useramount']);
        $q = print_r($hhh);
        echo $j=$q*100/$ytot;
    }
}

Upvotes: 1

Views: 125

Answers (4)

Jenz
Jenz

Reputation: 8369

You can process an array in PHP using foreach like shown below:

foreach (($hhh) as $v => $k)
{
echo $k*100/$ytot;
}

Here,

$hhh=explode(',',$row['yes_useramount']);

So $hhh will return an array of values from $row['yes_useramount'] which was imploded with ,.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173562

A simple foreach should do the trick:

foreach (explode(',', $row['yes_useramount']) as $q) {
    echo $q * 100 / $ytot;
}

Upvotes: 1

sunny
sunny

Reputation: 1166

Try this-

$resul=mysql_query("select * from post_bet where bet_id = '$id'")or die(mysql_error());
if(mysql_num_rows($resul)>0)
{
    while($row=mysql_fetch_assoc($resul))
    {
        $y_uid=$row['yes_userid'];          
        $y_uamt=$row['yes_useramount'];
        $n_uid=$row['no_userid'];
        $n_uamt=$row['no_useramount'];
        $ytot=$row['yes_total'];
        $ntot=$row['no_total'];
        $hhh=explode(',',$row['yes_useramount']);

    }


foreach($hhh as $val)
{
        echo $j=$val*100/$ytot;
}
}

Upvotes: 1

user3454436
user3454436

Reputation: 231

try this code in your script. If there having error please tell me here.

$resul=mysql_query("select * from post_bet where bet_id = '$id'")or die(mysql_error());
if(mysql_num_rows($resul)>0)
{
 while($row=mysql_fetch_assoc($resul))
{
 $y_uid=$row['yes_userid'];         
 $y_uamt[]=$row['yes_useramount'];
 $n_uid=$row['no_userid'];
 $n_uamt=$row['no_useramount'];
 $ytot=$row['yes_total'];
 $ntot=$row['no_total'];
}

for($i = 0; $i<count($y_uamt);$i++){

$sum_uamt = $sum_uamt + int($y_uamt[$i]);
}

echo $j = $sum_uamt * 100 / $ytot;

Upvotes: 0

Related Questions