Skip to content

Instantly share code, notes, and snippets.

@hirak
Created March 22, 2012 11:33
Show Gist options
  • Save hirak/2157806 to your computer and use it in GitHub Desktop.
Save hirak/2157806 to your computer and use it in GitHub Desktop.
配列か連想配列か判定する ref: http://qiita.com/items/721cc3a385cb2d7daebd
<?php
if (array_values($arr) === $arr) {
echo '$arrは配列';
} else {
echo '$arrは連想配列';
}
<?php
/**
* 添え字が0から連続する数値(=配列とみなせる)ときにtrue
*/
function is_vector(array $arr) {
return array_values($arr) === $arr;
}
$arr1 = array('a','b','c'); //配列
$arr2 = array('a'=>'a', 'b'=>'b'); //添字が文字なので配列とは言えない
$arr3 = array('a', 2=>'b', 1=>'c'); //添え字の順番がおかしいので配列とは言えない
var_dump(is_vector($arr1)); //true
var_dump(is_vector($arr2)); //false
var_dump(is_vector($arr3)); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment