SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Exercises (IV)

PHP Exercise #9

Function that prints an image

Write a function that prints an image, having as mandatory argument the URL of the image and optional arguments for width, height and alternative text.

<?php
function html_img($url, $width = 0, $height = 0, $alt = '') {
print '<img src="' . $url . '"';
if ($width) {
print ' width="' . $width . '"';
}
if ($height) {
print ' height="' . $height . '"';
}
print '>';
if (strlen($alt)) {
print ' alt="' . $alt . '"';
}
}
html_img('images/test/tin_hinan.gif', '300', '300', 'Tin Hinan, queen of the touareg');
?>
Tin Hinan, queen of the touareg

PHP Exercise #10

Function that prints an image

Modify the previous example so the file name can be passed to the function without having to specify the path, which will be stored in a global variable and attached to the file name inside the function.

<?php
$image_path = 'images/test/';
function html_img2($file, $width = 0, $height = 0, $alt = '') {
print '<img src="' . $GLOBALS['image_path'] . $file . '"';
if ($width) {
print ' width="' . $width . '"';
}
if ($height) {
print ' height="' . $height . '"';
}
if (strlen($alt)) {
print ' alt="' . $alt . '"';
}
print '>';
}
html_img2('tin_hinan.gif', '300', '300', 'Tin Hinan, queen of the touareg');
?>
Tin Hinan, queen of the touareg

PHP Exercise #11

Function that converts colors from RGB to HEX

The color identifiers used in HTML are created by joining together the hexadecimal values of red, green and blue. Write a function that accepts as arguments the decimal values for these colors and returns the equivalent hexadecimal value preceded by #. Use the dechex() function or the built-in hexadecimal-to-decimal conversion of sprintf().

<?php
function build_color($red, $green, $blue) {
$redhex = dechex($red);
$greenhex = dechex($green);
$bluehex = dechex($blue);
// It is necessary to use sprintf() to ensure that hexadecimal
// numbers of a single digit are completed with a 0 before them
return sprintf('#%02s%02s%02s', $redhex, $greenhex, $bluehex);
}
function build_color2($red, $green, $blue) {
// You can use as well the built-in hexadecimal-to-decimal
// conversion of sprintf() with the format character %x;
return sprintf('#%02x%02x%02x', $red, $green, $blue);
}
print build_color(156, 182, 225);
print nl2br("\n\n");
print build_color2(156, 182, 225);
?>
#9cb6e1

#9cb6e1