How to check an array is multidimensional or not in PHP?

How to check an array is multidimensional or not in PHP

Sometimes we need to check the array is multidimensional or not in the PHP. In this tutorial, we will learn different ways to check multidimensional array.

In this tutorial, we will discuss and check if array is multidimensional or not in PHP. We will look at example of PHP check array is multidimensional. We would like to share with you how to check if array is multidimensional PHP.

Let’s suppose we have an array in the application and we need to check that if it is multidimensional or not and based on we need to perform some activity in the application. There are few methods to check an array is multi-dimensional or not.

We have count() and rsort() function to check if the array is multidimensional or not in the PHP. count() function will produce the wrong result if the subarray is empty. So make sure while using the count() in this situation.

Let’s understand one by one from the below example

Check an array is multidimensional using rsort() function

Syntax:

rsort( $array )

Parameters: The rsort() function accepts one parameter

 Let’s see how we can check the multidimensional  array using rsort() function in the PHP.

<?php 
$mainArray = array( 
	
	// Default key for each will 
	// start from 0 
	array("atcodex", "to", "check"), 
	array("welcome", "World") 
); 

// Function to check array is 
// multi-dimensional or not 
function is_multi_array( $arr ) { 
	rsort( $arr ); 
	return isset( $arr[0] ) && is_array( $arr[0] ); 
} 

// Display result 
var_dump( is_multi_array( $mainArray ) ); 
?> 

Output:

bool(true)

Check an array is multidimensional using count() function

count ()

Another PHP program to check an array is multidimensional or not using count function. But as i mentioned above count() will not work if the sub array is empty.

<?php 
// Declare an array 
$data = array(1 => 'a', 2 => 'b', 3 => array("teach", "the", "student")); 
$gfg = array(1 => 'a', 2 => 'b'); 

// Function to check array is 
// multi-dimensional or not 
function is_multi($data) { 
	
	$rv = array_filter($data, 'is_array'); 
	
	if(count($rv)>0) return true; 
	
	return false; 
} 

// Display result 
var_dump(is_multi($data)); 
var_dump(is_multi($gfg)); 
?> 

Output:

bool(true)
bool(false)

Conclusion:

You can see and understand easily that how to know if array is Multidimensional. An array containing one or more array called a multidimensional array. We are tried to explain the article with possible example hope you liked it. If you have any query related to this, please comment below, we would love to help you.

You can also check PHP Multidimensional Array Search by Key and Value with Examples

Spread the love

Leave a Reply

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