user9073987
user9073987

Reputation:

PHP most efficient way to create an multidimensional array containing the values from list of values

Example

The input is an array of string something like

$strs = [
  "some string",
  "another string",
  // ...
];

The result should be:

$result = [
  [
     "somestring",
     true
  ],
  [
     "another string",
     true
  ]
];

The application is to create an array for the data provider to test phone numbers in unit tests.

I can do this very easily in a loop, but I am wondering if there is an array function for it.

My loop solution:

$result = [];
foreach($strs as $str) {
    $result[] = [$str, true];
}

Upvotes: 1

Views: 105

Answers (1)

Mohammad
Mohammad

Reputation: 21489

You can use array_map() instead

$strs = [
  "some string",
  "another string",
  // ...
];
$result = array_map(function($val){
    return [$val, true];
}, $strs);

Or using combination of array_map() and array_fill()

$result = array_map(null, $strs, array_fill(0, sizeof($strs), true));

Check result in demo

Upvotes: 2

Related Questions