Practical program exercise 10 PHP Converting word to digit for 12th computer applications
Program exercise 10 PHP Converting word to digit
Function:
- A function is created once but used many times, often from more than one program.
- If the function code changes, the changes are implemented in one spot (the function definition) while the function invocations remain untouched.
- This fact can significantly simplify code maintenance and upgrades, especially when contrasted with the alternative: manually changing every occurrence of the earlier code wherever it occurs (and possibly introducing new errors in the process).
Creating and Invoking Functions:
- Arguments, which serve as inputs to the function
- Return values, which are the outputs returned by the function
- The function body, which contains the processing code to turn inputs into outputs
explode()
- Splits a string into array elements explode() function, which accepts two arguments—the separator and the source string—and returns an array
Example:
<?php
$str = ‘tinker,tailor,soldier,spy’;
$arr = explode(‘,’, $str);
print_r($arr);
?>
foreach:
- The foreach construct provides an easy way to iterate over arrays.
- foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.
Switch Case:
- The switch case is an alternative to the if.. elseif..else statement which executes a block of code corresponding to the match.
Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
…
default:
code to be executed if n is different from all labels;
}
CA – 10 PHP – CONVERTING WORD TO DIGIT
QUESTION:
Write a PHP code to convert word to digit in PHP using function with switch…case.
AIM:
To Write a PHP program to convert word to digit.
PROCEDURE:
- Start Xampp server (Apache)
- Go to virtual path folder (C:\xampp\htdocs)
- Create digit.php file and type the program
- Execute the program on your Web browser using by this URL link (http://localhost/digit.php)
PROGRAM:
<html>
<body>
<?php
function word_digit($word)
{
$warr = explode(“;”,$word);
$result=”;
foreach($warr as $value)
{
switch(trim($value))
{
case ‘zero’ :
$result.=’0′;
break;
case ‘one’ :
$result.=’1′;
break;
case ‘two’ :
$result.=’2′;
break;
case ‘three’ :
$result.=’3′;
break;
case ‘four’ :
$result.=’4′;
break;
case ‘five’ :
$result.=’5′;
break;
case ‘six’ :
$result.=’6′;
break;
case ‘seven’ :
$result.=’7′;
break;
case ‘eight’ :
$result.=’8′;
break;
case ‘nine’ :
$result.=’9′;
break;
}
}
return $result;
}
echo word_digit(“zero;three;five;six;eight;one”).”<br>”;
echo word_digit(“seven;zero;one”);
?>
</body>
</html>
OUTPUT:
035681
701