I would suggest something similar, though with constants. I would also recommend that you use the regular control structures instead of the alternative syntax.
In fact, this is how I'd go around the same thing:
PHP Code:
<?php
define('JUDGE_ARRAY_ERROR', 0);
define('JUDGE_ARRAY_EMPTY', 1);
define('JUDGE_ARRAY_ASSOC', 2);
define('JUDGE_ARRAY_INDEX', 3);
define('JUDGE_ARRAY_MIXED', 4);
function judge_array_index(array $array) {
if(count($array) < 1) return JUDGE_ARRAY_EMPTY;
$HasStringKey = $HasNumericKey = false;
foreach($array as $key => $value){
if($HasNumericKey && $HasStringKey){
break;
}else if(!$HasNumericKey && is_integer($key)){
$HasNumericKey = true;
}else if(!$HasStringKey && is_string($key)){
$HasStringKey = true;
}
}
switch(true){
case $HasNumericKey && $HasStringKey:
return JUDGE_ARRAY_MIXED;
break;
case $HasNumericKey:
return JUDGE_ARRAY_INDEX;
break;
case $HasStringKey:
return JUDGE_ARRAY_ASSOC;
break;
default:
return JUDGE_ARRAY_ERROR;
break;
}
}
$array = array(0 => 'something', 'one' => 'tree', 'two' => 'other');
switch(Judge_Array_Index($array)){
case JUDGE_ARRAY_ASSOC:
echo 'It\'s associative.';
break;
case JUDGE_ARRAY_INDEX:
echo 'It\'s indexed.';
break;
case JUDGE_ARRAY_MIXED:
echo 'It\'s both.';
break;
case JUDGE_ARRAY_EMPTY:
echo 'It\'s empty.';
break;
case JUDGE_ARRAY_ERROR:
echo 'There was an error :O.';
break;
}
It can be laid out in a somewhat more concise fashion, but this is more learner-friendly.
Bookmarks