w3resource logo


php exercises

PHP functions - Exercises, Practice, Solution

rating Average rating 8 out of 10. Total 11 users rated.

<<PreviousNext>>

PHP functions [ 6 exercises with solution]

1. Create a function to calculate the factorial of a number (non-negative integer). The function accept the number as a argument. Go to the editor

<?php
function factorial_of_a_number($n)
{
  if($n ==0)
    {
	   return 1;
    }
  else 
    {	
	   return $n * factorial_of_a_number($n-1);
    }
	}
print_r(factorial_of_a_number(4));
?>

2. Create a function to check a number is prime or not. Go to the editor
Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

<?php
function IsPrime($n)
{
 for($x=2; $x<$n; $x++)
   {
      if($n %$x ==0)
	      {
		   return 0;
		  }
    }
  return 1;
   }
$a = IsPrime(3);
if ($a==0)
echo 'This is not a Prime Number.....';
else
echo 'This is  a Prime Number..';
?>

3. Create a function to reverse a string. Go to the editor

Click me to see the solution of Exercise No.- 3. Click me again to collapse.
<?php
function reverse_string($str1)
{
 $n = strlen($str1);
 if($n == 1)
   {
    return $str1;
   }
 else
   {
   $n--;
   return reverse_string(substr($str1,1, $n)) . substr($str1, 0, 1);
   }
}
print_r(reverse_string('1234'));
?>


4.
Create a function to sort an array. Go to the editor

Click me to see the solution of Exercise No.- 4. Click me again to collapse.
<?php
function array_sort(&$a)
{
 for($x=0;$x<count($a);++$x)
  {
    $min = $x;
  for($y=$x+1;$y<count($a);++$y)
   {
	 if($a[$y] < $a[$min] ) 
	 {
	   $temp = $a[$min];
	   $a[$min] = $a[$y];
	   $a[$y] = $temp;
	 }
	}
  }
 }
$a = array(51,14,1,21,'hj');
array_sort($a);
print_r($a);
?>

5. Create a PHP function that checks if a string is all lower case. Go to the editor

<?php
function is_str_lowercase($str1)
   {
    for ($sc = 0; $sc < strlen($str1); $sc++) {
	      if (ord($str1[$sc]) >= ord('A') &&
          ord($str1[$sc]) <= ord('Z')) {
      return false;
         }
         }
      return true;
       }
var_dump(is_str_lowercase('abc def ghi'));
var_dump(is_str_lowercase('abc dEf ghi'));
?>

6. Write a PHP function that checks whether a passed string is palindrome or not? Go to the editor
A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run.

<?php
function check_palindrome($string) 
{
  if ($string == strrev($string))
      return 1;
  else
	  return 0;
}
echo check_palindrome('madam');
?>

Go Top

Write your code here :

Go Top

More to Come !



<<PreviousNext>>