7
3

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 5 years have passed since last update.

array_mapで配列のindexを使う

Posted at

array_mapの第3引数にrange関数で数字の配列を作って渡すと配列自身のindexを渡しているわけではありませんが、良い感じになります。
その場合は第2引数引数と同じ要素数じゃないといけません。

<?php

$array = ['Laala', 'Mirei', 'Sophie']; 

$withNumberArray = array_map(function ($name, $index) {
    return sprintf('%d. %s', $index, $name);
}, $array, range(1, count($array)));

var_dump($withNumberArray);

array(3) {
  [0]=>
  string(8) "1. Laala"
  [1]=>
  string(8) "2. Mirei"
  [2]=>
  string(9) "3. Sophie"
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?