0
2

More than 1 year has passed since last update.

【PHP】in_arrayではなくissetとarray_key_existsを使おう

Last updated at Posted at 2023-01-16

in_arrayではなくissetとarray_key_existsを使おう

理由

  • in_arrayよりもissetやarray_key_existsの方が断然処理が早いから。

使用方法

issetの場合

$array = array(
                "orange" => true,
                "banana" => true,
                "lemon" =>true
                );
if(isset($array['orange'])){
    echo "これはオレンジです";
}

array_key_existsの場合

$array = array(
                "orange" => true,
                "banana" => true,
                "lemon" =>true
                );
if(array_key_exists("orange",$array)){
    echo "これはオレンジです";
}
  • 連想配列の作成は以下
// 対象となる配列
$array = array("orange","banana","melon");
$count = count($array);
$i = 0;
// trueの配列を作成
while($i < $count){
    $true[] = true;
    $i++;
}

// 連想配列
$associativeArray = array_combine($array,$true);

// isset
if(isset($associativeArray['orange'])){
    echo "isset_orange";
}

// array_key_exists
if(array_key_exists("orange",$associativeArray)){
    echo "array_key_exists";
}

スニペット

	"isset": {
		"prefix": "i",
		"body": [
			"\\$array = $1;",
			"\\$count = count(\\$array);",
			"\\$i = 0;",
			"while(\\$i < \\$count){",
				"\t\\$true[] = true;",
				"\t\\$i++;",
			"}",
			"\\$associativeArray = array_combine(\\$array,\\$true);",
			"if(isset(\\$associativeArray['$2'])){",
			"\t$3",
			"}",
		],
		"description": "issetを使用するための連想配列の作成"
	},
	"array_key_exists": {
		"prefix": "a",
		"body": [
			"\\$array = $1;",
			"\\$count = count(\\$array);",
			"\\$i = 0;",
			"while(\\$i < \\$count){",
				"\t\\$true[] = true;",
				"\t\\$i++;",
			"}",
			"\\$associativeArray = array_combine(\\$array,\\$true);",
			"if(array_key_exists(\"$2\",$associativeArray)){",
			"\t$3",
			"}",
		],
		"description": "array_key_existsを使用するための連想配列の作成"
	}
0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2