0

I'm trying to use array_search to find the key of a value in an array, I have the following simple code:

$current_user_existing_shopping_bag_string          = '1446784/-/3/-/£797.00(_)902982/-/4/-/£148.80(_) ';
$current_user_existing_shopping_bag_array           = explode('(_)', $current_user_existing_shopping_bag_string);
$key                                                = array_search($current_user_existing_shopping_bag_array, '902982');
echo $key;  

However I have no idea why this doesn't return the key of the value in the array, it should though. I've been trying various solutions for hours now and still no luck.

Anybody able to give me a pointer why this doesn't return the key for the value in the array?

Thanks

7
  • 1
    Do ( and ) have a special meaning in the explode() method? Commented Nov 17, 2014 at 16:05
  • what is your expected output? Commented Nov 17, 2014 at 16:06
  • It's used to separate the string elements into 'blocks' Commented Nov 17, 2014 at 16:06
  • My expected output is '1446784/-/3/-/£797.00' Commented Nov 17, 2014 at 16:06
  • 1
    array search takes the value (not the array) as first argument. Commented Nov 17, 2014 at 16:07

1 Answer 1

3

It is because array_search compares strings using === operator, not regex or strpos of any kind.

You search for 902982 but string is 902982/-/4/-/£148.80, and therefore they are not equal in any way.

For what you want to achieve, you can use preg_grep:

$result = preg_grep('/' . preg_quote($search) . '/', $current_user_existing_shopping_bag_array);

Then you can get the keys you need from the resulting array.

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

8 Comments

It is only filter-like regex search, and returns array indexed with original keys, so you can just take the keys you found and then delete them from the original array.
Okay, so I'm still a bit confused, the result I get in $result is an array
How I'm I supposed to use the info in this array?
@user2028856 Yes. $result has all elements of the original array with their respective key where the pattern was found (here: the number). So you can do sth like $.._bag_array = array_diff($.._bag_array, $result); to remove them from the original array
@user2028856 It contains key-value pairs from the original array, matching string you are searching. RTFM
|

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.