Asked 7 years ago
23 Dec 2016
Views 1011
noob

noob posted

how to check array is associative or not ?

still using mysql extension
get data by mysql_fetch_assoc , mysql_fetch_row or mysql_fetch_array , sometime i need to check i have associative fetch or row , array . so is there any way i can check array is associative or not dynamically ?
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

in php you can check by isset($array[0]) will tell you that is it index there or not means its not associative

or use below function to check it

function is_associative($array)
{
	$count = count($array);
	for ($i = 0; $i < $count; $i++) 
	{
		if (!array_key_exists($i, $array))
		{
			return true;
		}
	}
	return false;
}



usage
function is_associative return true if it associative else false
kord

kord
answered Jun 24 '23 00:00

you can use the array_keys function in PHP.


$row = mysqli_fetch_assoc($result); // Assuming $result is the result of a query

 
    $keys = array_keys($row);
    $isAssociative = !is_numeric($keys[0]);

    if ($isAssociative) {
        echo "The fetched array is associative.";
    } else {
        echo "The fetched array is not associative.";
    }
 

Post Answer