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?

2 Answers2

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
kuroi neko
  • 8,479
  • 1
  • 19
  • 43
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;
    }
  }
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
  • 1
    Please indent your code. I'm used to questioners not doing this, answerers should be better. – Barmar Jan 09 '14 at 08:31