Reputation: 311
I think I have a very easy question, but I am stuck anyway. I want to check if the value is in an array, and if it is, i want to change the variable value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, $test)){
$admin_is_menu = "true";
}
echo $admin_is_menu;
In the code above, it should output the echo "true"
, since "about"
is in the array. But is unfortunally does not work.
What am I doing wrong?
Upvotes: 1
Views: 77
Reputation: 14230
@cske pointed out in the comment how to do it. Here's a small explanation for that as well.
You should use array_column
. In this case array_column($test, "alias")
will return a new array:
array(2) {
[0]=>
string(5) "about"
[1]=>
string(4) "test"
}
Now, you check within it with in_array
:
in_array($admin_is_menu, array_column($test,'alias'))
and this will return true
Upvotes: 1
Reputation: 2096
Try array_column
to get all array value.
$admin_is_menu = "about";
$test = array();
$test = [
["Name" => "About","alias" => "about"],
["Name" => "Test", "alias" => "test"],
];
if(in_array($admin_is_menu, array_column($test,'alias'))){
$admin_is_menu = "true";
}
echo $admin_is_menu;
Upvotes: 1