enrico-dev
enrico-dev

Reputation: 155

PHP From string to two variables

In my db there is a table that have some values like this[string]

100/100
50/100
40/80
7/70

I need to change this values in

100%
50%
50%
10%

How can i do this using only PHP/mysql code?

EDIT:this is the code:

foreach ($html->find('div.stat') as $status_raw){
    $status = $tag_pic_raw->src;
    $status = mysql_real_escape_string($status);
    $data->query("INSERT IGNORE INTO `tb` (`value`) VALUES ('".$status."')");
}

I have used a DOM inspector to get info from another site

Upvotes: 0

Views: 80

Answers (4)

Charaf JRA
Charaf JRA

Reputation: 8334

Use explode() :Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter( / in this case).

$arr=array('80/100','50/100','40/80');
foreach($arr as $str){
 $values = explode('/',$str);
 echo ((int)$values[0]/(int)$values[1])*100.'%<br/>';
}

Upvotes: 0

Albzi
Albzi

Reputation: 15609

You can set up a function similar to this:

function math($one)
    {
        $new = explode("/", $one);
        $math = $new[0] / $new[1];
        $answer = $math * 100;
        return $answer."%";
    }

Then every time you need to query something, you can do it simply by doing this:

foreach ($results as $r)
{
    echo math($r);
}

This just makes it (I think) tidier and easier to read.

Upvotes: 0

Bad Wolf
Bad Wolf

Reputation: 8349

Used explode() combined with some math.

$str = '40/80';
$vals = explode('/', $str);
$percent = (($vals[0] / $vals[1]) * 100).'%';
echo $percent;

Upvotes: 4

XaxD
XaxD

Reputation: 1538

use explode() to divide up the values and then math them.

foreach($array as $val) // assuming all the (##/##) values are in an array
{
    $mathProblem = explode("/", $val);
    echo (intval($mathProblem[0]) / intval($mathProblem[1]) * 100)."%<br />";
}

Upvotes: 2

Related Questions