3

I want to come up with $desired_output from given $data array below using array_map() or any PHP array_* built-in function. Any idea how?

$data = array(
  'posted_name' => 'John Doe',
  'posted_age'  => '30',
);

$desired_output = array(
  'name' => 'John Doe',
  'age'  => '30',
);

I tried below but the result is an array of arrays:


$desired_output  = array_map(
    function($keys, $vals)
        {
            $new[substr($keys, strlen('posted_'))] = $vals;
            return $new;
    },
    array_keys($data),
    $data
);

print_r($desired_output );

/**
* Array (
  [0] => Array ( [name] => John Doe )
  [1] => Array ( [age] => 30 )
)
*/
4
  • array_map does a build in loop. the process is the same. Commented Nov 25, 2020 at 9:51
  • Iterating over array is always done via a loop. The thing is that loop is hidden under the hood and you won't see it. But it is stll a loop. Commented Nov 25, 2020 at 9:54
  • 2
    array_keys to get the keys, map or walk those to change the key names, and splice together with array_values again using array_combine …? Sounds like a lot of effort to “avoid” a simple, self-written loop IMHO. Commented Nov 25, 2020 at 10:11
  • @CBroe but that's how JavaScript is doing it nowadays! It's more functional™️ ! Would you dare to deny this wonderful trend? 😜 Commented Jul 27, 2022 at 16:03

2 Answers 2

7

What about the following:


$desired_output = array();
array_walk(
    $data,
    function(&$val, $key) use (&$desired_output)
    {
      $len = strlen('posted_');
      if (substr($key, 0, $len) == "posted_") {
        $key = substr($key, $len);
      }
      $desired_output[$key] = $val;
    }
);

print_r($desired_output);

Changes:

  • Using array_walk instead of array_map since _map cannot handle keys
  • Creating an empty array to build the result in
  • Using that array in the scope of the lambda function
  • Replacing the "posted_" only if it exists in the key

Output:

$ php -f ~/tmp/so2.php

Array
(
    [name] => John Doe
    [age] => 30
)
Sign up to request clarification or add additional context in comments.

1 Comment

I can't figure out why the $val argument is used by-reference (&) instead of by-value. Is it simply to not duplicate the array? Couldn't the & be removed if $val is always an object (aka already a reference).
0
$desired_output = array_combine(
    array_map( fn( $k ) => str_replace( 'posted_', '', $k ), array_keys( $data ) ),
    $data
);

1 Comment

Although this code might answer the question, I recommend that you also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.