Php Interview Program Questions Answer


$host = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($host, $username, $password);
//connect to server
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
<?php
if(isset($_POST['submit']))
{
$num1=$_POST['number1'];
$num2=$_POST['number2'];
$hcf = gcd($num1, $num2);
$lcm = ($num1*$num2)/$hcf;
}
function gcd($x, $y)
{
if ($x == 0) {
return $y;
}
while ($y != 0) {
if ($x > $y) {
$x = $x - $y;
}
else {
$y = $y - $x;
}
}
return $x;
}
?>
<html>
<head>
<title>LCM</title>
</head>
<body>
<table>
<form name="frm" method="post" action="">
<tr><td>Number1:</td><td><input type="text" name="number1" /></td></tr>
<tr><td>Number2:</td><td><input type="text" name="number2" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="submit" /></td> <td><center><span>
<?php
if(isset($_POST['submit']))
{
echo "LCM is ".$lcm;
}
?>
</span></center></td></tr>
</form>
</table>
</body>
</html>
We can get the first element of an array by the function current();
<?php
$arr = array('name'=>'angel','age'=>'23','city'=>'delhi','profession'=>'php developer');
$firstvalue = current($arr);
?>
OUTPUT : angel
<?php
$number = 6;
$fact = 1;
for($k=1;$k<=$number;++$k)
{
$fact = $fact*$k;
}
echo "Factorial of $number is ".$fact;
?>
OUTPUT : Factorial of 6 is 720
<?php
$x = 4;
$y = 3;
function fun($x = 3, $y = 4)
{
$z = $x+$y/$y+$x;
echo "$z";
}
echo $x;
echo $y;
echo $z;
fun($x, $y);
?>
OUTPUT: 439
<?php
$a = 10;
$b = 4;
$c = fun(10,4);
function fun($a,$b)
{
$b = 3;
return $a - $b + $b - $a;
}
echo $a;
echo $b;
echo $c;
?>
OUTPUT: 1400
<?php
$str = 1;
echo '$str is a value'; // OUTPUT : $str is a value
echo "$str is a value"; //OUTPUT : 1 is a value
?>
<?php
$a=3.1;
$b=true;
var_dump($a,$b);
?>
OUTPUT: float(3.1)
bool(true)
<?php
if(isset($_POST['sub']))
{
$rows=$_POST['row'];
for($i=$rows;$i>=1;--$i)
{
for($space=0;$space<$rows-$i;++$space)
echo " ";
for($j=$i;$j<=2*$i-1;++$j)
echo "* ";
for($j=0;$j<$i-1;++$j)
echo "* ";
echo "
";
}
}
?>
$date = date("Y-m-d H:i:s");
date("Y/m/d h:i:s", strtotime("+30 minutes", $date));
<?php
$a=15;
$b=10;
echo "The value of a is ".$a." and b is ".$b;
echo " before swapping.
";
$temp=$a;
$a=$b;
$b=$temp;
echo "The value of a is ".$a." and b is ".$b;
echo " After swapping
";
?>
OUTPUT: The value of a is 5 and b is 10 before swapping.
The value of a is 10 and b is 5 After swapping
<?php
$numbers=array(12,23,45,20,5,6,34,17,9,56);
$length=count($numbers);
$min=$numbers[0];
for($i=1;$i<$length;$i++)
{
if($numbers[$i]<$min)
{
$min=$numbers[$i];
}
}
echo "The smallest number is ".$min;
?>
OUTPUT: The smallest number is 5.
OUTPUT:
$b value will be 1
$c value will be 21 as 2 is concatenated to the value of $b.
<?php
for($i=0;$i<=5;$i++){
for($j=1;$j<=$i;$j++){
echo "* ";
}
echo "
";
}
?>
<?php
if(isset($_POST['submit']))
{
$year=$_POST['year'];
if($year%4==0)
{
echo "It is a leap year";
}
else
{
echo "It is not a leap year";
}
}
?>
<html>
<head>
<title>Leap year</title>
</head>
<body>
<form name="leapyear" action="" method="post">
Year :<input type="text" name="year" value="" required="">
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$value1=$_POST['num1'];
$value2=$_POST['num2'];
$value1=$value1+$value2;
$value2=$value1-$value2;
$value1=$value1-$value2;
echo "Value of first variable after swapping" .$value1."
";
echo "Value of second variable after swapping" .$value2;
}
?>
<html>
<head>
<title>Swap two values without third Variable</title>
</head>
<body>
<form name="factorial" action="" method="post">
Number 1 :<input type="text" name="num1" value="" required="">
Number 2 :<input type="text" name="num2" value="" required="">
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
<?php
if(isset($_POST['number']) && $_POST['number']!='')
{
$number = $_POST[ 'number' ];
// get the number entered by user $temp = $number;
$sum = 0;
while($temp != 0 )
{
$remainder = $temp % 10;
//find reminder $sum = $sum + ( $remainder * $remainder * $remainder );
$temp = $temp / 10;
}
if( $number == $sum )
{
echo "$number is an Armstrong Number";
}else
{
echo "$number is not an Armstrong Number";
}
}
?>
<html>
<head>
<title>Armstrong Number</title>
</head>
<body>
<table>
<form name="frm" method="post" action="">
<tr><td>Number:</td><td><input type="text" name="number" /></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Check" /></td>
<td>
<center><span>
<?php if(isset($_POST['sub']))
{if($check==0)
{echo "It is a Armstrong Number";
}
else
{
echo "It is not a Armstrong Number";}
}
?>
</span>
</center>
</td>
</tr>
</form>
</table>
</body>
</html>
<?php
if(isset($_POST['sub']))
{ $fibo=array(0,1);
$num=$_POST['nm1'];
for($i=2;$i<=$num-1;$i++)
{
$fibo[$i]=$fibo[$i-1]+$fibo[$i-2];
}
}
?>

</head>
<body>
<table>
<form name="frm" method="post" action="">
<tr><td>Number of Terms:</td><td><input type="text" name="nm1" /></td></tr>
<tr><td></td><td><input type="submit" name="sub" /></td>
<td><center><span>
<?php if(isset($_POST['sub'])){
for($i=0;$i<=$num-1;$i++){echo $fibo[$i].",";}
}
?>
</span></center>
</td></tr>
</form>
</table>
</body>
</html>
<?php
for($i = 1; $i<=5; $i++){
for($j = 1; $j<=5; $j++){
if($i == 1 || $i == 5){
echo "*";
}
else if($j == 1 || $j == 5){
echo "*";
}
else {
echo "  ";
}
}
echo "
";
}
?>
<?php
if(isset($_POST['sub']))
{
$row=$_POST['row'];
for($i=1;$i<=$row;$i++)
{
for($j=1;$j<=$i;$j++)
{
echo $j;
}
echo "
";
}
}
?>
<table>
<form method="post" name="frm" action="">
<tr> <td>Enter Number of rows:</td> <td><input type="text" name="row" /></td> </tr>
<tr><td></td> <td><input type="submit" name="sub" /></td> </tr>
</form>
</table>
<?php
$string="cakephp and zend";
$array =explode('and',$string);
print_r($array);
?>
<?php
$array = array('cakephp','zend');
$string =implode(' and ',$array);
echo $string;
?>
<?php
$string="hello and world";
echo strtoupper($string);
?>
<?php
$string="hello and world";
echo strtolower($string);
?>
<html>
<head>
<title> Number of times the web page has been viited.</title>
</head>
<body>
<?php
session_start();
if(isset($_SESSION['count']))
$_SESSION['count']=$_SESSION['count']+1;
else
$_SESSION['count']=1;
echo "<h3>This page is accessed</h3>".$_SESSION['count'];
?>
</body>
</html>
<html>
<body>
<center>
<h2> Check Given String Is Palindrom Or Not</h2>
<form action="" method="GET">
<h3> Enter String : <input type=text name=str><br> </h3>
<input type=submit value=submit name=Show>
<input type=reset value=Reset name=Reset>
</form>
</center>
</body>
<html>
<?php
$str1 = $_GET['str'];
$str2 = strrev($str1);
if(strcmp($str1,$str2) === 0)
echo "<h3> $str1 is palindrom </h3>";
else echo "<h3> $str1 is not palindrom </h3>";
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method='POST'>
<h2>Please input your name:</h2>
<input type="text" name="name">
<input type="submit" value="Submit Name">
</form>
<?php
//Retrieve name from query string and store to a local variable
$name = $_POST['name'];
echo "<h3> Hello $name </h3>";
?>
</body>
</html>
<?php
echo "Your User Agent is :" . $_SERVER ['HTTP_USER_AGENT'];
?>
<?php
$url = 'http://www.w3resource.com/php-exercises/php-basic-exercises.php';
$url=parse_url($url);
echo 'Scheme : '.$url['scheme']."\n";
echo 'Host : '.$url['host']."\n";
echo 'Path : '.$url['path']."\n";
?>
<?php
$text = 'PHP Tutorial';
$text = preg_replace('/(\b[a-z])/i','\1',$text);
echo $text;
?>
<?php
if (!empty($_SERVER['HTTPS']))
{
echo 'https is enabled';
}
else
{
echo 'http is enabled'."\n";
}
?>
<?php
header('Location: https://www.tutorialspoint.com/');
?>
<?php
// pass valid/invalid emails
$email = "mail@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '"' . $email . '" = Valid'."\n";
}
else
{
echo '"' . $email . '" = Invalid'."\n";
}
?>
<?php
$all_lines = file('http://www.cotocus.com/');
foreach ($all_lines as $line_num => $line)
{
echo "Line No.-{$line_num}: " . htmlspecialchars($line) . "\n";
}
?>
<?php
$current_file_name = basename($_SERVER['PHP_SELF']);
$file_last_modified = filemtime($current_file_name);
echo "Last modified " . date("l, dS F, Y, h:ia", $file_last_modified)."\n";
?>
<?php
$file = basename($_SERVER['PHP_SELF']);
$no_of_lines = count(file($file));
echo "There are $no_of_lines lines in $file"."\n";
?>
<?php
echo 'Current PHP version : ' . phpversion();
// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy')."\n";
?>
<?php
// current time
echo date('h:i:s') . "\n";
// sleep for 10 seconds
sleep(10);
// wake up
echo date('h:i:s')."\n";
?>
<?php
$full_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $full_url."\n";
?>
<?php
echo php_uname()."\n";
echo PHP_OS."\n";
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!'."\n";
}
?>
<?php
// Create a temporary file in the temporary
// files directory using sys_get_temp_dir()
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');
echo $temp_file."\n";
?>
<?php
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod())."\n";
?>
<?php
$my_array = array("red", "black", "green", "black", "white", "yellow");
$sorted_unique_array = array_values(array_unique($my_array));
print_r($sorted_unique_array);
?>
<?php
class MyClass {
public function __construct()
{
echo 'MyClass class has initialized !'."\n";
}
}
$userclass = new MyClass;
?>
<?php
class factorial_of_a_number
{
protected $_n;
public function __construct($n)
{
if (!is_int($n))
{
throw new InvalidArgumentException('Not a number or missing argument');
}
$this->_n = $n;
}
public function result()
{
$factorial = 1;
for ($i = 1; $i <= $this->_n; $i++)
{
$factorial *= $i;
}
return $factorial;
}
}
$newfactorial = New factorial_of_a_number(5);
echo $newfactorial->result();
?>
<?php
class user_message {
public $message = 'Hello All, I am ';
public function introduce($name)
{
return $this->message.$name;
}
}
$mymessage = New user_message();
echo $mymessage->introduce('Scott')."\n";
?>
<?php
$original = array( '1','2','3','4','5' );
echo 'Original array : '."\n";
foreach ($original as $x)
{echo "$x ";}
$inserted = '$';
array_splice( $original, 3, 0, $inserted );
echo " \n After inserting '$' the array is : "."\n";
foreach ($original as $x)
{echo "$x ";}
echo "\n"
?>
<?php
function min_values_not_zero(Array $values)
{
return min(array_diff(array_map('intval', $values), array(0)));
}
print_r(min_values_not_zero(array(-1,0,1,12,-100,1))."\n");
?>
<?php
$colors = array("Red", "Orange", "Black", "White");
rsort($colors);
print_r($colors);
?>
<?php
$colors = array( "Red", "Green", "Black", "White");
print_r($colors);
$lower_colors = array_map('strtolower', $colors);
print_r($lower_colors);
$upper_colors = array_map('strtoupper', $colors);
print_r($upper_colors);
?>
<?php
function array_uniq($my_array, $value)
{
$count = 0;
foreach($my_array as $array_key => $array_value)
{
if ( ($count > 0) && ($array_value == $value) )
{
unset($my_array[$array_key]);
}
if ($array_value == $value) $count++;
}
return array_filter($my_array);
}
$numbers = array(4, 5, 6, 7, 4, 7, 8);
print_r(array_uniq($numbers, 7));
?>
<?php
$colors = array('key1' => 'Red', 'key2' => 'Green', 'key3' => 'Black');
$given_value = 'Black';
print_r($colors);
$new_filtered_array = array_filter($colors, function ($element) use ($given_value) { return ($element != $given_value);});
print_r($filtered_array);
print_r($new_filtered_array);
?>
<?php
$sum = 0;
for($x=1; $x<=30; $x++)
{
$sum +=$x;
}
echo "The sum of the numbers 0 to 30 is $sum"."\n";
?>
<?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')."\n");
?>
<?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;
}
}
}
return $a;
}
$a = array(51,14,1,21,'hj');
print_r(array_sort($a));
?>
<?php
$odate = "2016-12-15";
$newDate = date("d-m-Y", strtotime($odate));
echo $newDate."\n";
?>
<?php
$dt = "2008-02-23";
echo 'First day : '. date("Y-m-01", strtotime($dt)).' - Last day : '. date("Y-m-t", strtotime($dt))."\n";
?>
<?php
var_dump(checkdate(2, 30, 2008));
var_dump(checkdate(2, 29, 2008));
?>
<?php
$dt = new DateTime();
$dt->sub(new DateInterval('P1D'));
echo $dt->format('F j, Y')."\n";
?>
<?php
$dt='2016-12-15';
$dt1 = strtotime($dt);
$dt2 = date("l", $dt1);
$dt3 = strtolower($dt2);
if(($dt3 == "saturday" )|| ($dt3 == "sunday"))
{
echo $dt3.' is weekend'."\n";
}
else
{
echo $dt3.' is not weekend'."\n";
}
?>
<?php
$s = 'The quick brown fox';
$arr1 = explode(' ',trim($s));
echo $arr1[0]."\n";
?>
<?php
for ($x = ord('a'); $x <= ord('z'); $x++)
echo chr($x);
echo "\n"
?>
<?php
$dt = DateTime::createFromFormat('m-d-Y', '12-08-2004')->format('Y-m-d');
echo $dt;
?>
<?php
$r;
$c;
for($r=1;$r<=5;$r++)
{
for($c=1;$c<=$r;$c++)
{
echo("$r");
}
echo "
";
}
?>
Two strings can be joined together by the use of a process called as concatenation. A dot (.) operator is used for this purpose.
<?php
$string1 = Hello;
$string2 = World;
$stringall = $string1.$string2;
echo $stringall;
?>
mysql_affected_rows() return the number of entries affected by an SQL query.
<?php
$_SERVER ['HTTP_USER_AGENT'] ;
?>
There is no special way to set persistent cookies. Setting Cookies with an expiration date become persistent cookie.
setcookie( "cookieName", 'cookieValue', strtotime( '+30 days' ) );
<?php
$numbers=array(12,23,45,20,5,6,34,17,9,56);
$n=count($numbers);
for ($c = 0 ; $c < ( $n - 1 ); $c++)
{
for ($d = 0 ; $d < ($n - $c - 1); $d++)
{
if ($numbers[$d] > $numbers[$d+1]) /* For decreasing order use < */
{
$swap = $numbers[$d];
$numbers[$d] = $numbers[$d+1];
$numbers[$d+1] = $swap;
}
}
}
echo "Sorted list in ascending order
";
for ( $c = 0 ; $c < $n ; $c++ )
echo $numbers[$c]." ";
?>
<?php
$colors = array(
"color1", "color20", "color3", "color2"
);
sort($colors, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($colors as $key => $val) {
echo "Colors[" . $key . "] = " . $val . "\n";
}
?>
<?php
function shuffle_assoc($my_array)
{
$keys = array_keys($my_array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $my_array[$key];
}
$my_array = $new;
return $my_array;
}
$colors = array("color1"=>"Red", "color2"=>"Green", "color3"=>"Yellow");
print_r(shuffle_assoc($colors));
?>
<?php
function letter_range($length)
{
$data_range = array();
$letters = range('A', 'Z');
for($i=0; $i<$length; $i++)
{
$position = $i*26;
foreach($letters as $ii => $letter)
{
$position++;
if($position <= $length)
$data_range[] = ($position > 26 ? $data_range[$i-1] : '').$letter;
}
}
return $data_range;
}
print_r(letter_range(8));
?>
<?php
for($x=1; $x<=10; $x++)
{
if($x< 10)
{
echo "$x-";
}
else
{
echo "$x"."\n";
}
}
?>
<?php
$dates = array('2015-02-01', '2015-02-02', '2015-02-03');
echo "Latest Date: ". max($dates)."\n";
echo "Earliest Date: ". min($dates)."\n";
?>
<?php
class MyCalculator {
private $_fval, $_sval;
public function __construct( $fval, $sval ) {
$this->_fval = $fval;
$this->_sval = $sval;
}
public function add() {
return $this->_fval + $this->_sval;
}
public function subtract() {
return $this->_fval - $this->_sval;
}
public function multiply() {
return $this->_fval * $this->_sval;
}
public function divide() {
return $this->_fval / $this->_sval;
}
}
$mycalc = new MyCalculator(12, 6);
echo $mycalc-> add()."\n"; // Displays 18
echo $mycalc-> multiply()."\n"; // Displays 72
echo $mycalc-> subtract()."\n"; // Displays 6
echo $mycalc-> divide()."\n"; // Displays 2
?>
<?php
$str1 = 'football';
$str2 = 'footboll';
$str_pos = strspn($str1 ^ $str2, "\0");
printf('First difference between two strings at position %d: "%s" vs "%s"',
$str_pos, $str1[$str_pos], $str2[$str_pos]);
?>
<?php
$numbers = array(12,23,45,20,5,6,34,17,9,56,999);
$length = count($numbers);
$max = $numbers[0];
for($i=1;$i<$length;$i++)
{
if($numbers[$i]>$max)
{
$max=$numbers[$i];
}
}
echo "The biggest number is ".$max;
?>