user3354912 user3354912 - 2 months ago 10
PHP Question

PHP: echo places all plain text parts after ones that came from variables

The following code resides in

functions.php
to deal with correct plural word form after a number:

function plural_form($number, $after) {
$cases = array (2, 0, 1, 1, 1, 2);
echo $number.' '.$after[ ($number%100>4 && $number%100<20)? 2: $cases[min($number%10, 5)] ];
}


And this one placed into
single.php
:

$last = new DateTime('2014-10-07');
$today = new DateTime();
$diff = $last->diff($today);

$years = $diff->format('%y');
$months = $diff->format('%m');
$days = $diff->format('%d');

$years_with_word = plural_form($years, array('year','years','years'));
$months_with_word = plural_form($months, array('month','months','months'));
$days_with_word = plural_form($days, array('day','days','days'));

echo "Last time I have coded without errors ".$years_with_word.", ".$months_with_word." and ".$days_with_word." ago.";


For some reason that is yet unknown to me, I've got the following output:


1 year11 months12 daysLast time I have coded without errors , and ago.


instead of


Last time I have coded without errors 1 year, 11 months and 12 days ago.


Seems that variables' values have priority over plain text ones.

That means I also can not wrap the output into any tag.

What could be the problem? Where I was wrong?

Answer

echo will dump the result to the page wherever it is called from a function. so instead of an echo use a return which will assign the value to a variable for later use.

<?php

function plural_form($number, $after) {
    $cases = array (2, 0, 1, 1, 1, 2);
    return $number.' '.$after[ ($number%100>4 && $number%100<20)? 2: $cases[min($number%10, 5)] ];
}

$last = new DateTime('2014-10-07');
$today = new DateTime();
$diff = $last->diff($today);

$years = $diff->format('%y');
$months = $diff->format('%m');
$days = $diff->format('%d');

$years_with_word = plural_form($years, array('year','years','years'));
$months_with_word = plural_form($months, array('month','months','months'));
$days_with_word = plural_form($days, array('day','days','days'));

echo "Last time I have coded without errors ".$years_with_word.", ".$months_with_word." and ".$days_with_word." ago.";

Last time I have coded without errors 1 year, 11 months and 11 days ago.