1

while doing array search in php array search

i need to search the key for the value blue

but key for both values purple, blue

when i try the following it shows nothing

$array = array(1 => 'orange', 2 => 'yellow', 3 => 'green', 4 => 'purple','blue');

$key = array_search('blue', $array);  

echo $key;

How to find the key for blue or do i need to change the $array?

9
  • possible duplicate of Sort Multi-dimensional Array by Value Commented Jan 9, 2014 at 8:17
  • @kumar_v He doesn't have a multi-dimensional array, it's just an ordinary associative array. Commented Jan 9, 2014 at 8:19
  • @StackExchange eval.in/87552 it's return 5 Commented Jan 9, 2014 at 8:21
  • A key can only have one value in an associative array. You're confused if you think that 4 is the key for both purple and blue. Commented Jan 9, 2014 at 8:22
  • @kumar_v anna i need to find the key as 4 when i search for purple or blue ! how to do this Commented Jan 9, 2014 at 8:22

2 Answers 2

1

First, the program you show as an example will output 5 as the key value for 'blue', as others have already pointed out.

Now if I understand what you might want, it's a way of having two elements referred to by the same index.

In that case you could simply swap keys and values, like so:

$array = array(
    'orange' => 1,
    'yellow' => 2,
    'green'  => 3,
    'purple' => 4,
    'blue'   => 4);

echo $array['purple']; // 4
echo $array['blue'  ]; // 4
Sign up to request clarification or add additional context in comments.

Comments

0

In this case the maximum user assigned key is 4 i.e. purple, so it will be 5 for blue eventually... and the code what you are using exactly returns the right output which is 5.

If you do print_r() of your array you will get the idea.. See here

Array
(
    [1] => orange
    [2] => yellow
    [3] => green
    [4] => purple
    [5] => blue
)

EDIT :

i need to find the key as 4 when i search for purple or blue ! how to do this

You cannot have a same key in an array or for two different values !

Instead modify your array like this...

<?php
$array = array(1 => 'orange', 2 => 'yellow', 3 => 'green', 4 => 'purple,blue'); //Adding purple and blue seperated by comma...

foreach($array as $k=>$v)
  {
   if(strpos($v,'purple')!==false)
    {
     echo $k;// "prints" 4 if you pass purple or blue !
     break;
    }
  }

1 Comment

Please indent your code. I'm used to questioners not doing this, answerers should be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.