2

I'm working on a function that uses a custom output format that is set by the user at the time of calling the function, similar to the date() function.

The data that this function is calling is returned from a database, so I needed a way to pair the letter the user uses in the pattern to the key from the table, this is what I came up with:

function getUserInfo($id, $pattern = "f, l") {

    //convert single letter format to key used in database
    $keys = ["f", "l", "u", "e"];
    $values = ["name_first", "name_last", "Username", "email"];
    $pattern = str_replace($keys, $values, $pattern);

    $user = [
        "uid" => 1,
        "Username" => "ldavid",
        "name_first" => "Larry",
        "name_last" => "David",
        "email" => "ldavid@example.com",
    ];
    foreach($user as $key => $info) {
        str_replace($key, $info, $pattern);
    }
    return $pattern;
}

The problem with this is converting the single letter fomrat to the key used in the database. To get around this, I could just have the user type in the exact key from the database, but I would much rather it just be a single letter.

In the code currently, I always get the output namemail_first, namemail_last. I think the problem is, when str_replace is called to convert the letters, the word "name" has an "e" in it, and is therefore being replaced by "email". Then, none of the keys match the key from the database so no more replacements are made.

I'm wondering if there is a better way to handle this logic, I'm kind of stuck on how to solve the issue. How can I properly replace the single letter provided by the user to the key from the database?


Edit: In the comments, it was suggested to use strstr(); upon doing this, I got an error:

Warning: strstr(): needle is not a string or an integer

$keys = ["f", "l", "u", "e"];
$values = ["name_first", "name_last", "Username", "email"];
$pattern = strstr($pattern, array_combine($keys,$values));
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71

0 Answers0