1

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?

5
  • 3
    in_array($admin_is_menu, array_column($test,'alias')) Commented Nov 7, 2016 at 12:48
  • That still echoes "about" Commented Nov 7, 2016 at 12:54
  • 1
    funny, it echo'd "true" for me. Commented Nov 7, 2016 at 12:56
  • 1
    and seeing an answer posted using the same coding, @cske should be posting an answer for it, or at the very least; given some credit. Commented Nov 7, 2016 at 13:01
  • I think I am doing some small thing wrong yes, cske had the right answer indeed! Unfortunally i cannot upvote his post , nor an unposted answer :( Commented Nov 7, 2016 at 13:08

2 Answers 2

1

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;

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.