Jump to content

Problem with array_search(


rmelino

Recommended Posts

Hello,

 

I've been struggling to figure this out and can't seem to make it work.

 

I'm using the array_search function.  The problem occurs when I am searching for a value that appears twice in the array.  In the example below, you'll see that '1-2-3' is the value for both 'Dog Brown' and 'Dog Black'.  When I post, I am only able to echo out 1-2-3 when the posted values are $animal = 'Dog' and $color = 'Brown'.  If i post $animal = 'Dog' and $color = 'Black' the it echoes out nothing.  I am assuming this is because '1-2-3' appears twice in the array and 'Dog Brown' is the first one in the array list?

 

Any help is greatly appreciated!

 

Thanks in advance...

 

if (isset($_POST['calculate']) || isset($_POST['calculate_x'])) {
$animal = ($_POST['animal']);	
$color = ($_POST['color']);	
}

$search = $animal.''.$color;

$array = array( 
'1-2-3' => 'Dog Brown',
'1-2-3' => 'Dog Black',
'4-5-6' => 'Cat Brown',
'7-8-9' => 'Bird Black' };

$result = array_search($search,$array);

echo $result;

Link to comment
https://forums.phpfreaks.com/topic/187056-problem-with-array_search/
Share on other sites

You could swap around the array keys and values, like:

 

$array = array(
    'Dog Brown'  => '1-2-3',
    'Dog Black'  => '1-2-3',
    'Cat Brown'  => '4-5-6',
    'Bird Black' => '7-8-9'
};

$result = 'No match';
if (isset($result[$search])) {
    $result = $result[$search];
}

echo $result;

Thanks Salathe.

 

This still isn't working for me because when I swap around the array keys and values my array_search function no longer works.

 

Perhaps I'm not fully understanding what you meant with this part of your code:

 

$result = 'No match';
if (isset($result[$search])) {
    $result = $result[$search];
}

echo $result;

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.