John Davidson

arrays - php array_search returning 0 for the first element?

0 comments
Message:


I have this code



$restaurant = array('/restaurant_pos/', '/bar_nightclub_pos/')
$current_page = $_SERVER['REQUEST_URI'];

if (array_search($current_page, $restaurant)) {
echo "KEEP ME";
}


the problem is the array_search is returning 0 because '/restaurant_pos/' is the first element in the array which is causing the if to fail...any ideas on how to check if the value is in the array without failing on the first element



My Answer:
You can use the strict comparison operator (===) to check if the value returned by array_search is not only present in the array but also at a different position than the first element. Here's an updated version of your code:

php
$restaurant = array('/restaurant_pos/', '/bar_nightclub_pos/');
$current_page = $_SERVER['REQUEST_URI'];

$key = array_search($current_page, $restaurant);

if ($key !== false) {
echo "KEEP ME";
}


By checking if $key is not strictly equal to false, you ensure that the if statement will only be true if the value is found in the array at a position other than the first element.

Rate this post

5 of 5 based on 8864 votes

Comments




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