1

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];
}
2
  • Possible duplicate of How to declare a two dimensional array most easily in PHP? Commented Oct 16, 2018 at 12:23
  • 1
    It is similar, but the answers are static, this one is dynamic. Commented Oct 16, 2018 at 12:36

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer. Though it does not say which is most efficient.
Efficiency is down to the underlying Php implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.