This question already has answers here:
PHP foreach change original array values [duplicate]
(5 answers)
Closed 3 years ago.
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 ?
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:
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);
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! :)
instead write this to print
var_dump($credentials_list);
if you are returning the value then no need to print_r or echo
Related
This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 6 years ago.
I have two functions that I am working with. The first one does a database call and grabs two attributes of a user. The UserID and Markup for that user.
/*
Search Markup for a specific QID
*/
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
}
}
return '';
}
/*
Fetch the markup data for this dashboard
*/
function fetchMarkup(){
global $dashboardID;
global $markupArray;
$objDB = new DB;
$objMarkup = $objDB
-> setStoredProc('FetchMarkup')
-> setParam('dashboardID', $dashboardID)
-> execStoredProc()
-> parseXML();
// Create an array of the markup
if(isset($objMarkup->data)){
$i = 0;
foreach($objMarkup->data as $m){
$markup[$i] = array();
$markup[$i]['QID'] = (string)$m->QID;
$markup[$i]['markup'] = (string)$m->Markup;
$i++;
}
$markupArray = $markup;
}
}
When I run fetchMarkup() and then print out $markupArray, I get the result of:
Array
(
[0] => Array
(
[QID] => Q0002
[markup] => success
)
[1] => Array
(
[QID] => Q101
[markup] => success
)
[2] => Array
(
[QID] => Q200
[markup] => info
)
)
My next step is to be able to search that array by providing a QID and having it return the markup value to me.
I am trying to so something like searchMarkup('Q0002') to have it tell me the result of markup but I am not getting any response.
How could I go about retrieving the value of markup from the array that is created by fetchMarkup() ?
why you are using $key ? which came from no where
foreach($markupArray as $m)
as you can see you alias $m not $key
And $markupArray is an associated array not an object array
So instead of
if((string)$key->QID == (string)$identifier){
return $m->markup;
}
since it is an associated array change it to
if((string)$key['QID'] == (string)$identifier){
return $m['markup'];
}
So your searchMarkup would be like this
function searchMarkup($identifier){
global $markupArray;
if(isset($markupArray)){
foreach($markupArray as $m){
if((string)$m['QID'] == (string)$identifier){
return $m['markup'];
}
}
}
return '';
}
Demo
This question already has answers here:
in_array() and multidimensional array
(24 answers)
Closed 8 years ago.
I'm a newb and I got a problem with in_array...
So this is my array $allUsers (received by a SQL-Query for Usernames)
Array
(
[0] => Array
(
[name] => test
)
[1] => Array
(
[name] => test2
)
[2] => Array
(
[name] => admin
)
[3] => Array
(
[name] => kingChräbi
)
Now If a new member wants to register, I want to check in this array if it's already existent:
if(!in_array($username,$allUsers)){....
eventhough it is to when $username is NOT in $allUsers do .... it's just skipping to else also if the user is existing :(
$username is set before with
$username = $_POST['name'];
and working as it should (i can echo it without a problem, is exactly test or test2 without whitespace or anything)
I really looked around alot, but I can't find anything like my problem here... Could you please help me?
Thanks
although question itself is quite silly, as you have to realize what array you are working with, the quick solution, based on PDO tag, would be as follows: instead of fetchAll() use fetchAll(PDO::FETCH_COLUMN)
Or, rather you need to learn SQL as well, and find users not by means of selecting them ALL from database which makes no sense, but by asking a database to find a user for you
$stm = $pdo->prepare("SELECT * FROM table WHERE name=?");
$stm->execute(array($_POST['name']));
$user = $stm->fetch();
if ($user) { // <---HERE YOU GO
The in_array() does not work with multi-dimensional arrays. You better flatten your array and then do a search for the keyword.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); //<-- Pass your array here
$new_arr = array();
foreach($it as $v) {
$new_arr[]=$v;
}
if(in_array('test',$new_arr))
{
echo "Exists !";
}
Working Demo
You are searching a 2-D array for a value under the key of "name".
Using array_map() or simple foreach loop should work -
$username = "admin";
$key = "name";
if(!in_array($username,array_map(function($v)use($key){return $v[$key];},$allUsers))){
echo "No found";
}else{
echo "Found";
}
If you are using:
While ($ row=mysql_fetch_assoc ($ result) {
$ data [] = $ row
}
Remove the [] to not create a multidimensional array.
This question already has answers here:
PHP array delete by value (not key)
(20 answers)
Closed 9 years ago.
I want to unset 1 element in the array.
If for example I use GET and ?group=k
How do I unset "k" in the array?
This is the array:
$groups_array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a2','b2','c2','d2','e2','f2');
I have tried
if(isset($_GET['group'])) {
unset($groups_array[1]);
$new_groupps_array = array_values($groups_array);
}
which works fine but where it shows [1] it needs to be a letter so I know how to unset it?
Hope you understand
many thanks
Example, if you wanted to delete 'a' value, you simply do:
$key = array_search('a', $groups_array); // search for key of my value
if($key !== false){
unset($groups_array[$key]);
}
Can you try this, You can use array_search function to retrieve the value based key and unset the array accordingly.
if(isset($_GET['group'])) {
$key = array_search ($_GET['group'], $groups_array);
unset($groups_array[$key ]);
$new_groupps_array = array_values($groups_array);
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does $k => $v in foreach($ex as $k=>$v) mean?
I am trying to understand what this means:
foreach($this->domains as $domain=>$users) {
// some code...
}
I understand $this->domains is an array that foreach will index over. But what does as $domain=>$users mean? I have only seen the => operator used in an array to set (key, value) pairs. The class has a member called $domain, but I assume that would be accessed as $this->domain.
The => operator specifies an association. So assuming $this->domains is an array, $domain will be the key, and $users will be the value.
<?php
$domains['example.com'] = 'user1';
$domains['fred.com'] = 'user2';
foreach ($domains as $domain => $user) {
echo '$domain, $user\n';
}
Outputs:
example.com, user1
fred.com, user2
(In your example, $users is probably an array of users);
Think of it this way:
foreach($this->domains as $key=>$value) {
It will step through each element in the associative array returned by $this->domains as a key/value pair. The key will be in $domain and the value in $users.
To help you understand, you might put this line in your foreach loop:
echo $domain, " => ", $users;
Read foreach
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each
loop, the value of the current element is assigned to $value and the
internal array pointer is advanced by one (so on the next loop, you'll
be looking at the next element).
The second form does the same thing, except that the current element's
key will be assigned to the variable $key on each loop.
$domain here is a local variable that contains the key of the current item in the array. That is if your array is:
$ages = array("dad" => 31, "mom" => 35, "son" => 2);
Then
foreach($ages as $name=>$age)
{
// prints dad is 32 years old, mom is 35 years old, etc
echo "$name is $age years old"
}
In the loop body, referring to $name would refer to the current key, ie "dad", "mom" or "son". And $age would refer to the age we've stored above at the current key.
assume that would be accessed as $this->domain.
You're right, just $domain is the local variable here. You need $this->domain to get the member variable.
I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )
There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.