user2696439
user2696439

Reputation:

How to search for a key in multi valued array in php array_search()?

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?

Upvotes: 1

Views: 119

Answers (2)

kuroi neko
kuroi neko

Reputation: 8661

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

Upvotes: 1

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;
    }
  }

Upvotes: 0

Related Questions