Showing posts with label PHP str_repeat. Show all posts
Showing posts with label PHP str_repeat. Show all posts

Tuesday, 2 June 2015

PHP: Convert an integer to roman-numeral

<?php function romanNumerals($num){ 
    
$n intval($num); 
    
$res ''; 

    
/*** roman_numerals array  ***/ 
    
$roman_numerals = array( 
        
'M'  => 1000, 
        
'CM' => 900, 
        
'D'  => 500, 
        
'CD' => 400, 
        
'C'  => 100, 
        
'XC' => 90, 
        
'L'  => 50, 
        
'XL' => 40, 
        
'X'  => 10, 
        
'IX' => 9, 
        
'V'  => 5, 
        
'IV' => 4, 
        
'I'  => 1); 

    foreach (
$roman_numerals as $roman => $number){ 
        
/*** divide to get  matches ***/ 
        
$matches intval($n $number); 

        
/*** assign the roman char * $matches ***/ 
        
$res .= str_repeat($roman$matches); 

        
/*** substract from the number ***/ 
        
$n $n $number; 
    } 

    
/*** return the res ***/ 
    
return $res; 
} 

echo 
romanNumerals(23); ?>

Monday, 29 September 2014

str_repeat in PHP

PHP str_repeat() function is utilized to repeat a input string for certain number of times.

Syntax:

str_repeat(string,repeat)
string : Required.Specifies the input string

repeat : Required. Specifies the how many times the string will be repeated. Must be greater than or equal to 0

Example:

<?php
echo str_repeat("Good Morning, ",3);
?>
Output will be:
Good Morning, Good Morning, Good Morning,