Calculate a string (cm) into (inch)

Viewed 28

I've a combined field with content "729.5 × 60.0 × 1864.0" cm that I need to split and calculate in "inches". The (cm) is not in the string.

I've already a function that works for single VARs:

function cm2in($cm2)
{
     $in = $cm2/2.54;
     return sprintf ($in);
}

But what is the best way to split the string above? Thanks for support!

1 Answers

Ok, solved it by myself.

<?php
$str = "729.5 × 60.0 × 1864.0";
print_r (explode("×",$str));
?> 

results in

Array ( [0] => 729.5 [1] => 60.0 [2] => 1864.0 )

From this I do now:

<?php $str = get_field( 'size' );
                            $cm = explode("×", $str);
                            $in[0] = cm2in($cm[0]); $in[1] = cm2in($cm[1]); $in[2] = cm2in($cm[2]); 
                            echo $cm[0] . "cm x" . $cm[1] . "cm x" . $cm[2] . "cm /" ;
                            echo $in[0] . "in x" . $in[1] . "in x" . $in[2] . "in" ;
                        ?>

In total this works like below

<?php

/* THIS IS THE PART IN THE PAGE */
$str = "231.0 × 190.0";
mm2in($str); // this is where the function is calling


/* THIS IS THE PART IN THE FUNCTIONS.PHP */

/* transforms MM into IN */
function mm2in($str) //this is the function that is called later
{
    $mm = explode("×", $str); // splits the string into single parts of mm[x]
    $in = explode("×", $str); // splits the string into single parts of in[x] for recalculation into in.
   foreach ($in as &$calc) {
    $calc = $calc*0.0393701; // calculates mm 2 inches
    $calc = substr($calc,0,5); // reduces the presented signs to 5 = eg 7.480 instead of 7.4801345
    }
    echo $mm[0] . " mm x " . $mm[1] . " mm (" . $in[0] . " in x " . $in[1] . " in)";
}

?>
Related