Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
How to sort an array in descending order in Ruby?
Next article icon

How to Check an Array is Sorted or Not in PHP?

Last Updated : 29 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array, the task is to check whether the given array is sorted or not. Arrays are often used to store and manipulate data. One common task is to check if an array is sorted in ascending or descending order. This article will explore different approaches to determine whether an array is sorted.

There are two main types of sorting orders to check:

  • Ascending order: Arrange the array elements from the smallest to the largest value, where each subsequent element is greater than or equal to the previous one.
  • Descending order: Arrange the array elements from the largest to the smallest value, where each subsequent element is less than or equal to the previous one.

These are the following approaches:

Table of Content

  • Iterative Comparison
  • Using sort and rsort functions

Iterative Comparison

The simplest way to check if an array is sorted is to iterate through the array and compare each element with the next one.

Example 1: Checking for Ascending Order.

PHP
<?php   function isArrSorted($arr) {       $n = count($arr);       for ($i = 0; $i < $n - 1; $i++) {           if ($arr[$i] > $arr[$i + 1]) {               return false;           }       }       return true;   }   // Driver Code   $arr = [1, 2, 3, 4, 5];    if(isArrSorted($arr)) {       echo "Sorted Array in Ascending Order.";   } else {       echo "Unsorted Array.";   } ?> 

Output
Sorted Array in Ascending Order.

Example 2: Checking for Descending Order.

PHP
<?php     function isArrSorted($arr) {         $n = count($arr);                  for ($i = 0; $i < $n - 1; $i++) {             if ($arr[$i] < $arr[$i + 1]) {                 return false;             }         }                 return true;     }     // Driver Code     $arr = [5, 4, 3, 2, 1];      if(isArrSorted($arr)) {         echo "Sorted Array in Descending Order.";     } else {         echo "Unsorted Array.";     } ?> 

Output
Sorted Array in Descending Order.

Using sort and rsort functions

Another approach is to sort a copy of the array and compare it with the original array. we will use sort() function to sort the array and then we will compare that to the original array to check whether

Example 1: Checking for Ascending Order using sort() function.

PHP
<?php     function isArrSorted($arr) {         $sortArr = $arr;         sort($sortArr);         return $arr === $sortArr;     }     // Driver Code     $arr = [1, 2, 3, 4, 5];      if(isArrSorted($arr)) {         echo "Sorted Array in Ascending Order.";     } else {         echo "Unsorted Array.";     } ?> 

Output
Sorted Array in Ascending Order.

Example 2: Checking for Descending Order by using rsort() function.

PHP
<?php     function isArrSorted($arr) {         $sortArr = $arr;         rsort($sortArr);         return $arr === $sortArr;     }     // Driver Code     $arr = [5, 4, 3, 2, 1];     if(isArrSorted($arr)) {         echo "Sorted Array in Descending Order.";     } else {         echo "Unsorted Array.";     } ?> 

Output
Sorted Array in Descending Order.

Next Article
How to sort an array in descending order in Ruby?

B

blalverma92
Improve
Article Tags :
  • Web Technologies
  • PHP

Similar Reads

  • How to check an element is exists in array or not in PHP ?
    An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods : Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP
    2 min read
  • How to sort an array in descending order in Ruby?
    In this article, we will discuss how to sort an array in descending order in ruby. We can sort an array in descending order through different methods ranging from using sort the method with a block to using the reverse method after sorting in ascending order Table of Content Sort an array in descend
    3 min read
  • How to get elements in reverse order of an array in PHP ?
    An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal. There are various ways to reverse the elements
    4 min read
  • How to Slice an Array in PHP?
    In PHP, slicing an array means taking a subset of the array and extracting it according to designated indices. When you need to extract a subset of elements from an array without changing the original array, this operation comes in handy. PHP comes with a built-in function called array_slice() to he
    2 min read
  • How to sort an Array in C# | Array.Sort() Method Set – 2
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method
    9 min read
  • How to Insert a New Element in an Array in PHP ?
    In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key. We can insert an element or item in an array using the below functio
    5 min read
  • Sort an array of dates in PHP
    We are given an array of multiple dates in (Y-m-d) format. We have to write a program in PHP to sort all the dates in the array in decreasing order. Examples : Input : array("2018-06-04", "2014-06-08", "2018-06-05") Output : 2018-06-05 2018-06-04 2014-06-08 Input : array("2016-09-12", "2009-09-08",
    2 min read
  • How to find the index of an element in an array using PHP ?
    In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approaches Table of Content Using array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing
    6 min read
  • How to reset Array in PHP ?
    You can reset array values or clear the values very easily in PHP. There are two methods to reset the array which are discussed further in this article. Methods: unset() Functionarray_diff() Function Method 1: unset() function: The unset() function is used to unset a specified variable or entire arr
    2 min read
  • How to Sort an Array of Objects Based on a Key in JavaScript ?
    In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order. Table of Content Using sort() methodUsing Custom Sorting FunctionUsing Lodash _.orderBy() MethodUsin
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences