loader image

PHP Program to perform array operations

Write a PHP program to create an array and store 10 names in the array. Do the following operations.

  1. Display the contents using for each statement.
  2. Display the array in a sorted order.
  3. Display the array without the duplicate elements
  4. Remove the last element and display
  5. Display the array in reverse order
  6. Search an element in the given array.
<html>

<body>
    <h1>Array Operations</h1>
    <form action="" method="post">
        <input type=radio name=choice value=display>Display Array<br />
        <input type=radio name=choice value=sort>Sorted Array<br />
        <input type=radio name=choice value=dupli>Without Duplicate<br />
        <input type=radio name=choice value=pop>Delete Last<br />
        <input type=radio name=choice value=rev>Array Reverse<br />
        <input type=radio name=choice value=search>Array Search<br /><br/>
        <input type=Submit>
</body>

</html>

<?php
if ($_POST) {
    $countries = array("Chile", "Colombia", "Pakistan", "Pakistan", "Italy","Chile", "Austria", "New Zealand", "United States");
    $val = $_POST['choice'];
    switch ($val) {
        case "display":
            foreach ($countries as $value)
                echo "<br>" . $value;
            break;
        case "sort":
            sort($countries);
            foreach ($countries as $value)
                echo "<br>" . $value;
            break;
        case "dupli":
            $uarray = array_unique($countries);
            foreach ($uarray as $value)
                echo "<br>" . $value;
            break;
        case "pop":
            array_pop($countries);
            foreach ($countries as $value)
                echo "<br>" . $value;
            break;
        case "rev":
            $revarr = array_reverse($countries);
            foreach ($revarr as $value)
                echo "<br>" . $value;
            break;
        case "search":
            echo "<br/><br/>Position - " . array_search("Italy", $countries, true);
            break;
    }
}
?>
Output
array 1 php
array 2 php
array 3 php
array 4 php
array 5 php
array 6 php
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Scroll to Top