Skip to content

Instantly share code, notes, and snippets.

@JakubTesarek
Last active March 16, 2018 11:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakubTesarek/d026f60d4baaef810228 to your computer and use it in GitHub Desktop.
Save JakubTesarek/d026f60d4baaef810228 to your computer and use it in GitHub Desktop.
Interview question for PHP developers
<?php
/*
Objectives:
- Create PHP script that will translate input data to expected output from example below.
- Calculate time complexity of your script
bonus: Implement solution that will not use pass-by-reference and will not use objects
*/
$input = [
'A' => 1,
'B_C' => 2,
'B_D' => 3,
'E_F_G' => 4,
'E_H' => 5
];
$expectedOutput = [
'A' => 1,
'B' => [
'C' => 2,
'D' => 3
],
'E' => [
'F' => [
'G' => 4
],
'H' => 5
]
];
@JakubTesarek
Copy link
Author

For some reason people find this interview question extremely challenging. Solution that uses objects or pass-by-reference is quite intuitive. But when you can't you those constructs, getting the right solution might be tricky.

@vrana
Copy link

vrana commented Aug 15, 2014

$output = array();
foreach ($input as $key => $value) {
  eval("\$output['" . str_replace("_", "']['", addcslashes($key, "'\\")) . "'] = " . var_export($value, true) . ";");
}

Am I hired?

@vrana
Copy link

vrana commented Aug 15, 2014

This seems longer than it should need to be:

function idx(array $array, $key, $default = null) {
  return (array_key_exists($key, $array) ? $array[$key] : $default);
}

function addKeysToOutput(array $output, array $keys, $value) {
  $key = array_shift($keys);
  $output[$key] = ($keys
    ? addKeysToOutput(idx($output, $key, array()), $keys, $value)
    : $value);
  return $output;
}

$output = array();
foreach ($input as $key => $value) {
  $output = addKeysToOutput($output, explode("_", $key), $value);
}

@dg
Copy link

dg commented Aug 15, 2014

$tmp = [];
foreach ($input as $k => $v) {
    foreach (array_reverse(explode('_', $k)) as $k) {
        $v = [$k => $v];
    }
    $tmp[] = $v;
}
$output = call_user_func_array('array_merge_recursive', $tmp);

@ironer
Copy link

ironer commented Aug 16, 2014

$output = [];

function parseEl($k, $v) {
    return [$k[0] => isset($k[2]) ? parseEl(substr($k, 2), $v) : $v];
}

foreach ($input as $k => $v) {
    $output = array_merge_recursive($output, parseEl($k, $v));
}

@x0ffmos
Copy link

x0ffmos commented Aug 16, 2014

foreach($input as $k => $v)
    eval("\$output['".str_replace('_',"']['",$k)."']=$v;");

@foglcz
Copy link

foglcz commented Aug 17, 2014

OK, didn't want to post it here initially, but for the record ;)

https://gist.github.com/foglcz/07ce7e1a1c29bcf28bf6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment