-1

I am asking a question that I feel has no answer and I am curious as to why.

I have a test products array that lists all my people get_products_all().

function get_products_all() {   
$products = array();
$products[101] = array(
    "name" => "Jared",
    "age" => 23,
    "sex" => "Male");
$products[102] = array(
    "name" => "Gen",
    "age" => 21,
    "sex" => "Female");
$products[103] = array(
    "name" => "Noah",
    "age" => 24,
    "sex" => "Male");
return $products;
}

I then have a search function that pulls all of the products from get_products_all() and loops through the products to find a string in the "name" field that matches the search

   function get_products_search($s) {
    $results = array();
    $all = get_products_all();

    foreach($all as $product) {
    if (stripos($product["name"], $s)) {
        $results[] = $product;
    }
}
return $results;
}

As you can see, $s is the parameter I wish to search by. In this case, lets say Im searching for "Jared". Whenever I run this code, it tells me there is no one named "Jared" in my array! However when I just insert "ared"... it finds "Jared" just fine... If I put a space in front of "Jared" in the name field in the array, then it also works just fine.

My question is this: why doesn't stripos recognize the first character in the name field? Even when I use an offset of 0 it doesn't seem to include the first character. Is there any way around this?

I just want to be able to search for names without having to put a space in front of the name value.

Paul R
  • 208,748
  • 37
  • 389
  • 560
jlango7
  • 3
  • 2
  • If there is no way to include the first character, (i.e "0" in the string) in my formula above using **stripos**, is there another way to search for an entire string without having to put a space in front of the name value? E.g $products[101] = array( "name" => "(space)Jared", "age" => 23, "sex" => "Male"); – jlango7 Mar 15 '15 at 22:45

1 Answers1

3

According to the PHP manual:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Try

if (stripos($product["name"], $s) !== false) {

instead

Miqi180
  • 1,670
  • 1
  • 18
  • 20
  • I apologize firstly for not recognizing the obvious... "0" can return a boolean value...for anyone else reading this, the above answer worked for me. I now realize there are other questions that answer this topic... Thanks Miqi180! – jlango7 Mar 16 '15 at 00:29