PHP Assignment 2


1. Write a PHP Script to find the maximum value from array.

Ans:

<?php

$arr=array(10,20,30,50,60);
$temp=0;
for($i=0;$i<count($arr);$i++)
{

if($temp<$arr[$i])
{
$temp=$arr[$i];
}

}
echo “Maximum value of array:”.$temp;

?>


2. Write a PHP Script to find minimum value from array.

Ans:

<?php

$arr=array(10,20,30,50,60);
$temp=$arr[0];
for($i=0;$i<count($arr);$i++)
{

if($temp>$arr[$i])
{
$temp=$arr[$i];
}

}
echo “Manimum value of array:”.$temp;

?>

 



3. Write a PHP Script to arrange the array elements in ascending order.

Ans:

<?php

$arr=array(20,50,40,90,10);

for($i=0;$i<count($arr);$i++)
{

for($j=$i+1;$j<count($arr);$j++)
{

if($arr[$i]>$arr[$j])
{

$temp=$arr[$i];
$arr[$i]=$arr[$j];
$arr[$j]=$temp;

}

}

}
for($i=0;$i<count($arr);$i++)
{
echo $arr[$i].”,”;
}

?>


 


4. Write a PHP Script to arrange the array elements in descending order.

Ans:

<?php

$arr=array(20,50,40,90,10);

for($i=0;$i<count($arr);$i++)
{

for($j=$i+1;$j<count($arr);$j++)
{

if($arr[$i]<$arr[$j])
{

$temp=$arr[$i];
$arr[$i]=$arr[$j];
$arr[$j]=$temp;

}

}

}
for($i=0;$i<count($arr);$i++)
{
echo $arr[$i].”,”;
}

?>

 


5. Write a PHP Script to find the prime number from array.

Ans:

<?php

$arr=array(1,2,3,4,5,6,7,8,9,10);
for($i=0;$i<count($arr);$i++)
{

$counter=0;
for($j=2;$j<$arr[$i];$j++)
{

if($arr[$i]%$j==0)
{
$counter=1;
break;
}

}
if($counter==0)
{
echo “$arr[$i],”;
}

}

?>

 


6. Write a PHP Script to find the non prime number from array.

Ans:

<?php

$arr=array(1,2,3,4,5,6,7,8,9,10);
for($i=0;$i<count($arr);$i++)
{

$counter=0;
for($j=2;$j<$arr[$i];$j++)
{

if($arr[$i]%$j==0)
{
$counter=1;
break;
}

}
if($counter==1)
{
echo “$arr[$i],”;
}

}

?>

 

 


7. Write a PHP Script to find the sum of even numbers from array

Ans:

<?php

$arr=array(1,2,3,4,5,6,7,8,9);
$sum=0;
for($i=0;$i<count($arr);$i++)
{

if($arr[$i]%2==0)
{
$sum=$sum+$arr[$i];
}

}
echo “Sum of even:”.$sum;

?>

 


8. Write a PHP Script to find the sum of odd numbers from array.

Ans:

<?php

$arr=array(1,2,3,4,5,6,7,8,9);
$sum=0;
for($i=0;$i<count($arr);$i++)
{

if($arr[$i]%2==1)
{
$sum=$sum+$arr[$i];
}

}
echo “Sum of odd:”.$sum;

?>

 


9. Write a PHP Script to find average of array elements.

Ans:

<?php

$arr=array(1,2,3,4,5,6,7,8,9);
$sum=0;
for($i=0;$i<count($arr);$i++)
{
$sum=$sum+$arr[$i];
}
$avg=$sum/count($arr);
echo “Avg of array:”.$avg;

?>

 


10.Write a PHP Script to merge the two array.

Ans:

<?php

$a=array(10,20,30);
$b=array(40,50);

for($i=0;$i<count($a)+count($b);$i++)
{

for($j=0;$j<count($a);$j++)
{
$c[]=$a[$j];
}
for($j=0;$j<count($b);$j++)
{
$c[]=$b[$j];
}

}
for($i=0;$i<count($a)+count($b);$i++)
{
echo $c[$i].”,”;
}

?>