0

My array looks like this:

array( '0|500|0.50', '501|1000|0.75' );

I am trying to run a search to get the KEY which has the searched value.

I made this function to search:

function cu_array_search($str,$array){
    foreach($array as $key => $value) {
        if(strstr($str,$value)) {
            return true;
        } else {
            return false;
        }
    }
}

and using it like this when checking:

if (cu_array_search(500,$array) {

but it never return true, despite that 500 exists in first key in array .

How to resolve this?

Thanks

4 Answers 4

2

strpos will make you function return true even that's 0.5001 but not 500.

You should explode the value by |, then check whether the number in the array.

function cu_array_search($num, $array){
  return count(array_filter($array, function ($var) use ($num) {
    return in_array($num, explode('|', $var));
  })) > 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

The haystack is the first argument, not the second:

if(strstr($value,$str)) {

Additionally, strpos is faster at this, so you should use:

function cu_array_search($str,$array){
    foreach($array as $key => $value) {
        if(strpos($value,$str) !== false) {
            return $key;
        } else {
            return false;
        }
    }
}

1 Comment

@AhmedFouad You should use xdazz's solution, there are cases where string searching might retrieve incorrect results for your scenario.
0

First, strstr parameters are wrong

Second, return false should be at the end of the loop.

Third, If you need KEY then You need to use return $key instead of return true

function cu_array_search($str,$array){
    foreach($array as $key => $value) {
        if(strstr($value, $str)) {
            return $key;
        }
    }
    return false;
}

Comments

0

This works fine

<?php

function cu_array_search($str, $array) {
    foreach($array as $key => $value) {
        $temp_array=explode('|', $value);
        if (in_array($str, $temp_array))
            return true;
    }
    return false;
}

$array = array( '0|500|0.50', '501|1000|0.75' );


if (cu_array_search(500, $array))
    echo "success";
else
    echo "failed" ;

?>

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.