w3resource

PHP function Exercises: Check whether a number is prime or not

PHP function: Exercise-2 with Solution

Write a function to check whether a number is prime or not.

Note: A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Pictorial Presentation:

PHP function Exercises: Check whether a number is prime or not

Sample Solution:

PHP Code:

<?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.....'."\n";
else
echo 'This is a Prime Number..'."\n";
?>

Sample Output:

This is a Prime Number..

Flowchart :

Flowchart: Check whether a number is prime or not

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.
Next: Write a function to reverse a string.

What is the difficulty level of this exercise?



PHP: Tips of the Day

Get first key in a (possibly) associative array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info.

You can use reset and key:

reset($array);
$first_key = key($array);

It's essentially the same as your initial code, but with a little less overhead, and it's more obvious what is happening.

Just remember to call reset, or you may get any of the keys in the array. You can also use end instead of reset to get the last key.

If you wanted the key to get the first value, reset actually returns it:

$first_value = reset($array);

There is one special case to watch out for though (so check the length of the array first):

$arr1 = array(false);
$arr2 = array();
var_dump(reset($arr1) === reset($arr2)); // bool(true)

Ref : https://bit.ly/32ecxHN