How to Sort Array by Key and Value in PHP?

How to Sort Array by Key and Value in PHP

In this post you will learn about How to Sort Array by Key and Value in PHP?. Read this below article carefully and understand this to put impact in real life.

Here we are going to know that how to sort a PHP Array by its Key and Value in this article. There are several built-in PHP functions for sorting an array. Sort(), rsort(), asort(), arsort(), ksort(), and krsort() are some of the functions available. Each of the above functions has the same purpose of delivering an array that has been sorted, but the way they are sorted differs.

  • sort() – Sorts the array from left to right in ascending order.
  • rsort() is a function that sorts an array in descending order.
  • asort() – This function sorts an array of keys in ascending order by their value.
  • arsort() – This function sorts an array of keys in descending order by their value.
  • ksort() – This function sorts an array of keys in ascending order by key.
  • krsort() – This function sorts an array of keys in descending order by key.

I’ll provide an example PHP source code here. A static random array is used in the programme. It will show the real array as well as two panels, one for the array’s original sort, which will be presented in a table, and the other for the freshly sorted data, which will be displayed according to the value entered in the sort form.

Table of Contents

Example

For a better look of the programme, I utilized bootstrap in the source code. The Bootstrap Library is available for download at getbootstrap.com.

Full Source Code

Save the file below as index.php

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sorting An Array</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <script src="./js/bootstrap.min.js"></script>
    <style>
        :root {
            --bs-success-rgb: 71, 222, 152 !important;
        }
 
        html,
        body {
            height: 100%;
            width: 100%;
            font-family: Apple Chancery, cursive;
        }
 
        .btn-info.text-light:hover,
        .btn-info.text-light:focus {
            background: #000;
        }
    </style>
</head>
 
<body class="bg-light">
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
        <div class="container">
            <a class="navbar-brand" href="https://sourcecodester.com">
            Sourcecodester
            </a>
 
            <div>
                <b class="text-light">Sorting An Array</b>
            </div>
        </div>
    </nav>
    <div class="container py-5" id="page-container">
 
        <?php
        $random_array = [1=>'purchase',2=>'aim',3=>'revise',4=>'continue',5=>'rid'];
        ?>
        <h4 class="fw-bold">Actual Array</h4>
        <div class="w-100 bg-gradient bg-dark text-light py-5 px-3">
            <pre class="w-100 m-0 h-100" contenteditable='true'><?= "[".(implode(",",$random_array))."]" ?></pre>
        </div>
        <hr>
        <?php 
            $sort = isset($_GET['sort']) ? $_GET['sort'] : 'key';
            $dir = isset($_GET['dir']) ? $_GET['dir'] : 'asc';
        ?>
        <div class="row justify-content-center">
            <div class="col-lg-5 col-md-7 col-sm-12 my-3">
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title">Sorting Form</h5>
                    </div>
                    <div class="card-body">
                        <form action="">
                            <div class="row align-items-end">
                                <div class="col-md-4 form-group">
                                    <label for="sort" class="control-label">Sort By</label>
                                    <select name="sort" id="sort" class="form-select form-select-sm">
                                        <option value="key" <?= $sort == 'key' ? 'selected' : '' ?>>Key</option>
                                        <option value="value" <?= $sort == 'value' ? 'selected' : '' ?>>Value</option>
                                    </select>
                                </div>
                                <div class="col-md-4 form-group">
                                    <label for="dir" class="control-label">Sort Dir</label>
                                    <select name="dir" id="dir" class="form-select form-select-sm">
                                        <option value="asc" <?= $dir == 'asc' ? 'selected' : '' ?>>Ascending</option>
                                        <option value="desc" <?= $dir == 'desc' ? 'selected' : '' ?>>Descending</option>
                                    </select>
                                </div>
                                <div class="col-md-4 form-group">
                                    <button class="btn btn-flat btn-primary bg-gradient">Sort</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <h3 class="fw-bold">Original Sort</h3>
            </div>
            <div class="col-md-6">
                <h3 class="fw-bold">Sorted</h3>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6 bg-secondary bg-gradient bg-opacity-50 border py-5 text-light">
                <table class="table table-striped table-bordered">
                    <colgroup>
                        <col width="10%">
                        <col width="90%">
                    </colgroup>
                    <thead>
                        <tr class="bg-gradient bg-primary text-light">
                            <th class="text-center">Key</th>
                            <th class="text-center">Value</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($random_array as $k => $v): ?>
                            <tr class="">
                                <td class="text-center"><?= $k ?></td>
                                <td><?= $v ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="col-md-6 bg-secondary bg-gradient bg-opacity-50 border py-5 text-light">
                <?php 
 
                if($sort =='value'){
                    if($dir == 'asc'){
                        asort($random_array);
                    }else{
                        arsort($random_array);
                    }
                }else{
                    if($dir == 'asc'){
                        ksort($random_array);
                    }else{
                        krsort($random_array);
                    }
                }
                ?>
                <table class="table table-striped table-bordered">
                    <colgroup>
                        <col width="10%">
                        <col width="90%">
                    </colgroup>
                    <thead>
                        <tr class="bg-gradient bg-primary text-light">
                            <th class="text-center">Key</th>
                            <th class="text-center">Value</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($random_array as $k => $v): ?>
                            <tr class="">
                                <td class="text-center"><?= $k ?></td>
                                <td><?= $v ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

Final Words

In this post you learnt about How to Sort Array by Key and Value in PHP?. If you like this article please share with your friends and family to support our website. We wrote this article by researching on internet to find best content for you. You can find more articles like this on our website for free. We provided you some important tips regarding this topic by following them you can easily understand. If you need more information regarding How to Sort Array by Key and Value in PHP? you can ask in comments or you can contact us via contact us form available on this website. Thanks for reading and sharing.


3 Comments on “How to Sort Array by Key and Value in PHP?”

  1. I was very happy to discover this website. I want to to thank you for your time due to this fantastic read!! I definitely liked every little bit of it and i also have you book marked to check out new things on your blog.

  2. Likewise, our assignment writers across the globe are well trained in their selected field which means you can conveniently place your confidence in the means they treat your paper, regardless of which academic self-control you’re from. When it comes to your career leads and bright future, takes the obligation on itself to advertise your development in the right direction. So, that way you would not need to hesitate before trusting us with your scholastic papers. Put an order with us currently as well as gain the incentives of wonderfully created scholastic documents today.

Leave a Reply

Your email address will not be published. Required fields are marked *