0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

初心者向け 少し便利なPHP関数

Posted at

はじめに

2つの配列があり、一つをキーにしてもう一つを値にして配列を作り直したい時

<?php
    $array1 = [ "a", "b", "c" ] ;
    $array2 = [ "1", "2", "3" ] ;
		
    // こういう配列を作りたい
    $combineArray = [
        "a" => "1",
        "b" => "2",
        "c" => "3"
     ];
?>

解決策

PHP7.2には、array_combine()と言う関数あり、これを使うだけで簡単に実現できます。

{.php}
<?php
   // 配列
  $array1 = [ "a", "b", "c" ] ;
	$array2 = [ "1", "2", "3" ] ;

	// 実行
	$result = array_combine($array1, $array2) ;

	// 返り値
	print_r( $result ) ;
?>

結果

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

以上です。

公式リファレンス

https://www.php.net/manual/ja/function.array-combine.php

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?