0

I have an array full of credentials following this pattern:

Array (
    [0] : Array (
        "login" => "toto"
        "passwd" => "mdpsecrethashe"
    )
    [1] : Array (
        "login" => "titi"
        "passwd" => "supermdp"
    )
    [2] : Array (
        [...]
    )
    [...]
)

I want to get the desired credentials thanks to the login and change the password. Here is my attempt:

function getListWithModifiedPassword($credentials_list, $wanted_login, $new_password){
    echo(print_r($credentials_list, TRUE));
    foreach ($credentials_list as $credentials)
        if ($credentials['login'] === $wanted_login)
            $credentials['passwd'] = hash('whirlpool', $new_password);
    echo(print_r($credentials_list, TRUE));
    return $credentials_list;
}

Assignation on line 5 doesn't want to work whatever the value (no change between the two echo(print_r($credentials_list, TRUE));, even though the condition on line 4 is true (tested: if I replace line 5 with echo "Hello world\n"; it works).

What is happenning in here ?

A Mehmeto
  • 1,594
  • 3
  • 22
  • 37

2 Answers2

0

instead write this to print

var_dump($credentials_list);

if you are returning the value then no need to print_r or echo

Rajkumar Sharma
  • 554
  • 1
  • 4
  • 9
0

In PHP's foreach loop you are working with copy of the array. So your assignation to $credentials['passwd'] does not take effect for $credentials_list.

You have 2 options:

  1. pass to the foreach reference value (notice & before $credentials in foreach bracket and also unset function which stops accidental assignation to the variable after foreach - see docs):
foreach($credentials_list as &$credentials) {
    if ($credentials['login'] === $wanted_login)
            $credentials['passwd'] = hash('whirlpool', $new_password);
}
unset($credentials);
  1. assign value directly into original array:
foreach($credentials_list as $key => $credentials) {
    if ($credentials['login'] === $wanted_login)
        $credentials_list[$key]['passwd'] = hash('whirlpool', $new_password);
}

Have a good day! :)

Marek Hulka
  • 241
  • 2
  • 3