This should be easy, but I can´t seem to get it to work. I have an multidimensional array and I wan´t iterate trough the array and check for a specific value. If the value equals a string then echo out a value of the array.
Here is the array and two values (the full array has a lot more):
$users = array(
"username01" => array("fullname" => "Firstname Lastname",
"status" => "Online"),
"username02" => array("fullname" => "Firstname Lastname",
"status" => "Offline")
);
I wan't to echo
out the Full name of each user that is "Online". Here is what I'm using today but it's not working:
$string = "Online";
foreach ($users as $username => $data) {
$fullname = $data["fullname"];
$status = $data["status"];
echo $status."= ";
if ($status == $string) {
echo "Yes";
} else {
echo "No";
}
echo "<br>";
}
If I echo out $fullname
and $status
the correct data is printed out. But for some reason the IF statement is not working. If the user is Offline the echo is "No", but if the user is Online there is no echo at all.
EDIT - Solved
Updated the array keys with quotes and $data[...] as was suggested below. I found a typo that was causing a false output. Thanks for all the help.
This is working okay for me :
<?php
//you forgot to enclose your keys by Single Quote (')
$users = array(
"username01" => array('fullname' => "Firstname Lastname",
'status' => "Online"),
"username02" => array('fullname' => "Firstname Lastname",
'status' => "Offline")
);
$string = "Online";
foreach ($users as $username => $data) {
//Notice this line
//$username is the key
//at the first iteraiton it will be uername01
//$data holds the array of username index in the array named $users
$fullname = $data["fullname"];
$status = $data['status'];
if($status == $string) { echo "Yes"; } else { echo "No"; }
}
?>
Go through foreach in php to know more details about foreach.
Hope that helps. Happy coding.
odd - looks like it should work...
try this:
$users = array(
"username01" => array( 'fullname' => "Firstname Lastname",
'status' => "Online"),
"username02" => array( 'fullname' => "Firstname Lastname",
'status' => "Offline")
);
foreach ( $users as $user )
{
if( strcasecmp( 'online', $user['status'] ) == 0 )
{
echo $user['fullname'] .': Online';
}
else
{
echo $user['fullname'] .': Offline';
}
}
Maybe it has something to do with the missing quotes around "fullname" and "status" in the array definition. The code you printed is working, but it throws warnings.
Try it like so:
<?php
$users = array(
"username01" => array("fullname" => "Firstname Lastname",
"status" => "Online"),
"username02" => array("fullname" => "Firstname Lastname",
"status" => "Offline")
);
Your problem is your array. Give this a try.
$users = array(
"username01" => array( "fullname" => "Firstname Lastname",
"status" => "Online"),
"username02" => array( "fullname" => "Firstname Lastname",
"status" => "Offline")
);
You forgot "
for status
and fullname
. Works on my local XAMPP like it should.