Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Abe Layee
Abe Layee
8,378 Points

How do I get the index value of two dimensional array in PHP

I am trying to get the index value of two dimensional array and campare it to a user login and password. if the password and username matche, i print out welcome. I know i need a database for this, but I am trying to store the user password and username in two dimensional array then compare the value in the array. Something like this, but is not working. I am new to php and I've been try to get my feet wet.

<?php 

    $user_name = $_POST['username'];
    $user_password = $_POST['userPassword'];

  $user_info = array("John"=>"css", "David'=>"html', "Solo"=>"Js");

    foreach($user_info as $value=> $user_value) {

}
//

if(user_info[$value] === $user_name && user_info[$value] === $user_password) {
 echo "Welcome ";
}
 else {
    echo "invalid info"; 
}

?>

4 Answers

You need to have the IF conditional inside the foreach and then only reference it by the "$value" and "$user_value" variables.

You also had a ' instead " after html.

/// <?php

$user_name = $_POST['username'];
$user_password = $_POST['userPassword'];

$user_info = array(
    "John"=>"css",
    "David'=>"html",
    "Solo"=>"Js"
 );

foreach($user_info as $value=> $user_value) {

    if($value === $user_name && $user_value === $user_password) {
        echo "Welcome ";
    } else {
        echo "invalid info"; 
    } //end if

} //end foreach

?> ///

Hopefully this should work for you.

Abe Layee
Abe Layee
8,378 Points

Thank you very much, but can you please explain this part to me

<?php 
 if($value === $user_name && $user_value === $user_password)// why use $value and user_value

// compare to mine
if(user_info[$value] === $user_name && user_info[$value] === $user_password)
?>

I am guessing the $value is for user name and the $user_password for password?

When you're inside the foreach and you are looping through the $user_info array as $value (key / "name") and $user_value (value / "password") you should use these to run your checks with.

If you use it outside you'll get an error as $value is not anywhere apart from inside the foreach.

Abe Layee
Abe Layee
8,378 Points

Thank you very much and I appreciate it

No trouble, hope it helped