Help us understand the problem. What is going on with this article?

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

はじめに

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

<?php
    $array1 = [ "a", "b", "c" ] ;
    $array2 = [ "1", "2", "3" ] ;

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

解決策

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

<?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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした