How to store the result in a variable to use later? - PHP

Asked

Viewed 67 times

0

How can I store the result of this code within a variable? I want to store in a variable so I can display the result at any time using <?php echo $row['resultado']; ?> for example.

Follow the code below and the DEMO in Extendsclass for testing:
https://extendsclass.com/php-bin/4eb56d4 (Click RUN to run)

<?php

$data1 = '2021-02-23 00:00:00';
$data2 = date('Y-m-d H:i:s', strtotime("-3 hours", strtotime("now")));
 
$unix_data1 = strtotime($data1);
$unix_data2 = strtotime($data2);

$nHoras   = ($unix_data2 - $unix_data1) / (60 * 60);
$nMinutos = (($unix_data2 - $unix_data1) % (60 * 60)) / 60;
 
printf('%02d:%02d', $nHoras, $nMinutos);

// Exemplo do que preciso, mas dessa forma não dá certo:
// $resultado = printf('%02d:%02d', $nHoras, $nMinutos);
// echo $resultado;

?>

1 answer

1

Use the function sprintf, which returns the string instead of printing.

<?php

$data1 = '2021-02-23 00:00:00';
$data2 = date('Y-m-d H:i:s', strtotime("-3 hours", strtotime("now")));
 
$unix_data1 = strtotime($data1);
$unix_data2 = strtotime($data2);

$nHoras   = ($unix_data2 - $unix_data1) / (60 * 60);
$nMinutos = (($unix_data2 - $unix_data1) % (60 * 60)) / 60;
 
// printf('%02d:%02d', $nHoras, $nMinutos);

$resultado = sprintf('%02d:%02d', $nHoras, $nMinutos);
echo "Hora: {$resultado}"

?>

DEMO

Browser other questions tagged

You are not signed in. Login or sign up in order to post.