現在の言語: 日本語

戻る

配列内検索(2)
配列関連

値やキーを探す関数として下記の関数があります。
関数使用可能バージョン内容
in_array()4.0.0+値が配列内にあるかを true / false で返します。
array_search()4.0.5+値が見つかった場合にそのキーを返し、見つからない場合は false を返します
array_find()8.4+自由な「条件」
その要素の 値

[サンプル]

copy
class test1
{
	//in_array
	function test1()
	{
		$ary=[1,"2",3];
		$this->judgeInArray($ary, 2, false, "(int)");//memo:(int) value:2 true
		$this->judgeInArray($ary, 2, true, "(int)");//memo:(int) value:2 false
		$this->judgeInArray($ary, "2", true, "(string)");//memo:(string) value:2 true
	}
	//in_array判定処理
	//ary:判定する配列
	//option:型を比較するかどうか?
	//false:比較しない
	//true:比較する
	private function judgeInArray(array $ary, $value, bool $option, string $memo)
	{
		if(in_array($value, $ary, $option))
		{
			echo "memo:$memo value:$value true".PHP_EOL;
		}
		else
		{
			echo "memo:$memo value:$value false".PHP_EOL;
		}
	}
	//array_search
	function test2()
	{
		$ary=[
			"key1" => 1,
			"key2" => 2,
			"key3" => 3
		];
		$this->judgeArraySearch($ary, 2, false, "(int)");//memo:(int) value:2 true
		$this->judgeArraySearch($ary, 2, true, "(int)");//memo:(int) value:2 true
		$this->judgeArraySearch($ary, "2", true, "(string)");//memo:(string) value:2 false

		//ver8.4以降
/*
		$user_roles = [
			'admin' => '管理者',
			'editor' => '編集者',
			'guest' => '閲覧者'
		];
		
		$key = array_search('編集者', $user_roles);
		// $key の中身は 'editor' になる
*/
	}
	//array_search判定処理
	//ary:判定する配列
	//option:型を比較するかどうか?
	//false:比較しない
	//true:比較する
	private function judgeArraySearch(array $ary, $value, bool $option, string $memo)
	{
		if(array_search($value, $ary, $option))
		{
			echo "memo:$memo value:$value true".PHP_EOL;
		}
		else
		{
			echo "memo:$memo value:$value false".PHP_EOL;
		}
	}
	//array_find
	function test3()
	{
		$ary =[1, 10, 100];
		//ver8.2のためarray_find()の代替処理としてjudgeArrayFind関数で判定
		//このサンプルでは>(より大きいか?)を判定するサンプルです
		$this->judgeArrayFind($ary, 10, fn($data, $value) => $value > $data, false, "(int)");//memo:(int) Result: FOUND(value:100)
//judgeArrayFindInArrayElementAll
/*
memo:(int) checked_value:1 -> false
memo:(int) checked_value:10 -> false
memo:(int) checked_value:100 -> true
*/
		$this->judgeArrayFind($ary, 10, fn($data, $value) =>  $value > $data, true, "(int)");//memo:(int) Result: FOUND(value:100)
//judgeArrayFindInArrayElementAll
/*
memo:(int) checked_value:1 -> false
memo:(int) checked_value:10 -> false
memo:(int) checked_value:100 -> true
*/
		$this->judgeArrayFind($ary, "10", fn($data, $value) =>  $value > $data, true, "(string)");//memo:(string) Result: NOT FOUND
//judgeArrayFindInArrayElementAll
/*
memo:(string) checked_value:1 -> false
memo:(string) checked_value:10 -> false
memo:(string) checked_value:100 -> false
*/
		//ver8.4以降
/*
		$users = [
			['id' => 1, 'name' => '田中', 'score' => 70],
			['id' => 2, 'name' => '佐藤', 'score' => 95], // ← これを探したい
			['id' => 3, 'name' => '鈴木', 'score' => 85],
		];
		
		// スコアが90点以上の最初のユーザー情報を取得
		$result = array_find($users, function($user) {
			return $user['score'] >= 90;
		});
		
		// $result の中身: ['id' => 2, 'name' =>佐藤', 'score' => 95]
*/
	}
	//array_find判定処理
	//ary:判定する配列
	//data:判定に使用するデータ
	//fn:コールバック関数
	//option:型を比較するかどうか?
	//false:比較しない
	//true:比較する
	private function judgeArrayFind(array $ary, $data, callable $fn, bool $option, string $memo)
	{
		$foundValue = null;
		$type = get_debug_type($data);
	
		foreach ($ary as $value) {
			// 型チェックが有効な場合、型が一致しなければこの要素はスキップ
			if ($option === true && get_debug_type($value) !== $type) {
				continue; 
			}
	
			// コールバック関数で条件判定
			if ($fn($data, $value)) {
				$foundValue = $value; // 見つかった値を保持
				break; // 見つかったのでループ終了
			}
		}
	
		// 全てのループが終わった後の判定
		if ($foundValue !== null) {
			echo "memo:$memo Result: FOUND(value:$foundValue)" . PHP_EOL;
		} else {
			echo "memo:$memo Result: NOT FOUND" . PHP_EOL;
		}
		return $foundValue;
	}
	private function judgeArrayFindInArrayElementAll(array $ary, $data, callable $fn, bool $option, string $memo)
	{
		$found = null;
		$type = get_debug_type($data);
		$flg = 0;
		foreach ($ary as $value)
		{
			$match = false;
			
			// 型と条件の両方をチェック
			if ($option === true) {
				if (get_debug_type($value) === $type && $fn($data, $value))
				{
					$match = true;
				}
			} else {
				if ($fn($data, $value))
				{
					$match = true;
				}
			}
		
			// 全要素の結果を出す
			$status = $match ? "true" : "false";
			echo "memo:$memo checked_value:$value -> $status" . PHP_EOL;
		}
	}
}
echo "<pre>";
$cls1= new test1();
$cls1->test1();
$cls1->test2();
$cls1->test3();
echo "</pre>";
copy
class test1
{
	//in_array
	function test1()
	{
		$ary=[1,"2",3];
		$this->judgeInArray($ary, 2, false, "(int)"); //memo:(int) value:2 true
		$this->judgeInArray($ary, 2, true, "(int)"); //memo:(int) value:2 false
		$this->judgeInArray($ary, "2", true, "(string)"); //memo:(string) value:2 true
	}
	//in_array judgment process
	//ary: Array to be judged
	//option: Whether to compare types?
	//false: don't compare 
	//true: compare 
	private function judgeInArray(array $ary, $value, bool $option, string $memo) 
	{ 
		if(in_array($value, $ary, $option)) 
		{ 
			echo "memo:$memo value:$value true".PHP_EOL; 
		} 
		else 
		{ 
			echo "memo:$memo value:$value false".PHP_EOL; 
		} 
	} 
	//array_search 
	function test2() 
	{ 
		$ary=[ 
		"key1" => 1, 
		"key2" => 2, 
		"key3" => 3 
		]; 
		$this->judgeArraySearch($ary, 2, false, "(int)");//memo:(int) value:2 true 
		$this->judgeArraySearch($ary, 2, true, "(int)");//memo:(int) value:2 true $this->judgeArraySearch($ary, "2", true, "(string)"); //memo:(string) value:2 false
		
		//Version 8.4 and later
/*
		$user_roles = [
		'admin' => 'Administrator',
		'editor' => 'Editor',
		'guest' => 'Viewer'
		];
		
		$key = array_search('Editor', $user_roles);
		// The value of $key will be 'editor'
*/
	}
	//array_search judgment process
	//ary: Array to be judged
	//option: Whether to compare types?
	//false: Do not compare
	//true: Compare
	private function judgeArraySearch(array $ary, $value, bool $option, string $memo)
	{
		if(array_search($value, $ary, $option))
		{
			echo "memo:$memo value:$value true".PHP_EOL;
		}
		else
		{
			echo "memo:$memo value:$value false".PHP_EOL;
		}
	}
	//array_find
	function test3()
	{
		$ary =[1, 10, 100];
		//In version 8.2, the judgeArrayFind function is used as an alternative to array_find().
		//This sample tests for > (greater than)
		$this->judgeArrayFind($ary, 10, fn($data, $value) => $value > $data, false, "(int)"); //memo:(int) Result: FOUND(value:100)
		//judgeArrayFindInArrayElementAll
/*
		memo:(int) checked_value:1 -> false
		memo:(int) checked_value:10 -> false
		memo:(int) checked_value:100 -> true
*/ 
		$this->judgeArrayFind($ary, 10, fn($data, $value) => $value > $data, true, "(int)");//memo:(int) Result: FOUND(value:100)
		//judgeArrayFindInArrayElementAll
/*
		memo:(int) checked_value:1 -> false
		memo:(int) checked_value:10 -> false
		memo:(int) checked_value:100 -> true
*/ 
		$this->judgeArrayFind($ary, "10", fn($data, $value) => $value > $data, true, "(string)"); // memo:(string) Result: NOT FOUND
		//judgeArrayFindInArrayElementAll
/*
		memo:(string) checked_value:1 -> false
		memo:(string) checked_value:10 -> false
		memo:(string) checked_value:100 -> false
*/
		//Version 8.4 and later
/*
		$users = [
		['id' => 1, 'name' => 'Tanaka', 'score' => 70],
		['id' => 2, 'name' => 'Sato', 'score' => 95], // ← Search for this
		['id' => 3, 'name' => 'Suzuki', 'score' => 85],
		];
		
		// Get the first user with a score of 90 or higher
		$result = array_find($users, function($user) {
		return $user['score'] >= 90;
		});
		
		// Contents of $result: ['id' => 2, 'name' => Sato', 'score' => 95]
*/
		}
		//array_find judgment process
		//ary: Array to be judged
		//data: Data to use for judgment
		//fn: Callback function
		//option: Whether to compare types?
		//false: Do not compare
		//true: Compare
		private function judgeArrayFind(array $ary, $data, callable $fn, bool $option, string $memo)
		{
			$foundValue = null;
			$type = get_debug_type($data);
			
			foreach ($ary as $value) {
				// If type checking is enabled, skip this element if the type does not match.
				if ($option === true && get_debug_type($value) !== $type) {
				continue;
			}
			
			// Test the condition using the callback function.
			if ($fn($data, $value)) {
				$foundValue = $value; // Keep the found value.
				break; // End the loop because a value was found.
			}
		}
		
		// Test after all loops have finished.
		if ($foundValue !== null) {
			echo "memo:$memo Result: FOUND(value:$foundValue)" . PHP_EOL;
		} else {
			echo "memo:$memo Result: NOT FOUND" . PHP_EOL;
		}
		return $foundValue;
	}
	private function judgeArrayFindInArrayElementAll(array $ary, $data, callable $fn, bool $option, string $memo)
	{
		$found = null;
		$type = get_debug_type($data);
		$flg = 0;
		foreach ($ary as $value)
		{
			$match = false;
			
			/ Check both type and condition
			if ($option === true) {
				if (get_debug_type($value) === $type && $fn($data, $value))
				{
				$match = true;
				}
			} else {
				if ($fn($data, $value))
				{
				$match = true;
				}
			}
		
			/ Retrieve results for all elements
			$status = $match ? "true" : "false"; 
			echo "memo:$memo checked_value:$value -> $status" . PHP_EOL; 
		} 
	}
}
echo "<pre>";
$cls1= new test1();
$cls1->test1();
$cls1->test2();
$cls1->test3();
echo "</pre>";

phpでコールバックを使用する場合は
function
fn
のいずれかで実装する必要があります。
get_debug_type()はPHP 8.0以降で使用可能です。
より正確な型名を返します。
従来の gettype() が抱えていた「現代のPHP開発とのズレ」を解消し、
より開発者が期待する直感的な情報を返せるようになっています。
(例)

データgettype()get_debug_type()
※php ver 8.0以降
100integerint
1.5doublefloat
new DateTime()objectDateTime
fopen("test.txt", "r")resourceresource(steam)


戻る

著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームページおよびアプリ等を利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。