How to check for multidimensional nature of an array in PHP

PHPServer Side ProgrammingProgramming

The ‘rsort’ function can be used to check if an array is multidimensional or not. It takes one parameter, i.e the array that needs to be checked and returns yes or no depending on the nature of the array.


 Live Demo

$my_array = array(
   array("This", "is", "a", "sample"),
   array("Hi", "there")
function multi_dim( $my_arr )
   rsort( $my_arr );
   return isset( $my_arr[0] ) && is_array( $my_arr[0] );
echo "Is the array multi-dimensional? ";
var_dump( multi_dim( $my_array ) );


Is the array multi-dimensional? bool(true)

An array is defined that contains string elements. A function named ‘multi_dim’ is defined that sorts the elements of the array using ‘rsort’. The ‘isset’ function is then used to perform ‘AND’ operation on the elements of the array. This would help understand if the array has a single dimension or is multi-dimensional.

Published on 02-Jul-2020 06:28:08