John Davidson

Check Member of an Associative array In PHP

0 comments
Message:


I created an array as follows.


<?php
$Users = [
"user1" => [
"UserName" => "Ahabiby" ,
"Password" => "12345678"
],
"user2" => [
"UserName" => "admin" ,
"Password" => "admin"
],
"user3" => [
"UserName" => "MohammadQ" ,
"Password" => "z12345678"
],
"user4" => [
"UserName" => "sobhan" ,
"Password" => "mz1235"
],
"user5" => [
"UserName" => "ewqfw" ,
"Password" => "qwscwcqq"
],
"user6" => [
"UserName" => "adminKoskesh" ,
"Password" => "UWOEIW"
]
];

My problem is how to create a structure when the two variables $username and $password are given to this structure in the array, first compare the $username completely with the "UserName" line in the array, and if there is a $password, compare it with the "Password" values in the array. Also check if the inputs are $username and $password if they were not in the array at all.


I wrote the code snippet myself, but it does not work perfectly because I do not want to add a feature that compares the inputs in the array if they are not complete.


<?php
$username = "MohammadQ";
$password = "z12345678";
foreach(array_column($Users,"UserName") as $key){
if($username == $key){
foreach(array_column($Users,"Password") as $key){
if($password == $key){
echo "Bingo!";
exit();
}
}
}
}
?>


My Answer:
php
$colors = array(
'red' => '#FF0000',
'green' => '#00FF00',
'blue' => '#0000FF'
);


To check if a specific key exists in the associative array, you can use the `array_key_exists()` function in PHP. Here's an example:

php
if (array_key_exists('red', $colors)) {
echo 'The key "red" exists in the array.';
} else {
echo 'The key "red" does not exist in the array.';
}


This will output: `The key "red" exists in the array.`

You can replace `'red'` with any other key you want to check for in the array.

Rate this post

3 of 5 based on 8580 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us