Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@pyon141

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

More than 1 year has passed since last update.

はじめに

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

0
Help us understand the problem. What is going on with this article?
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
pyon141

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?