Skip to content
Advertisement

array_search returns NULL/blank

I have such array

<?php
$a = array(
    "apple"=>"uniqid1",
    "apple"=>"uniqid2",
    "apple"=>"uniqid3",
    "bannana"=>"uniqid4"
    );

echo array_search("uniqid1", $a, true);

?>

When I search for “uniqid4” it returns “bannana” (all good)

But when I search for “uniqid1” it returns blank/NULL (I know there are duplicates – but array is as it is)

My question is :

How to search for “uniqid1” or “uniqid2” or “uniqid3” and get “apple” everytime?

based on first to answers:

If i reverse array:

$a=array(

"uniqid1"=>"apple",
"uniqid2"=>"apple",
"uniqid3"=>"apple",
"uniqid4"=>"bannana");

how to search uniqid3or uniqid2 or uniqid1

echo array_search("uniqid3",$a, true);

and get apple everytime?

Advertisement

Answer

As ArSeN said, you cannot use the same apple index multiple times. In doing so, PHP will understand that only the third exists, the first two will be ignored because they use the same key.

Maybe there is a way to make this work, and it would be by changing keys and values, then keys would become values.

The code would look like this:

<?php

$array = array(
    'uniqid1' => 'apple',
    'uniqid2' => 'apple',
    'uniqid3' => 'apple',
    'uniqid4' => 'bannana'
);

echo $array['uniqid1'];
echo '<br>';
echo $array['uniqid2'];
echo '<br>';
echo $array['uniqid3'];
echo '<br>';
echo $array['uniqid4'];

?>

Output

apple
apple
apple
bannana

As you can see, keys have become values, and it is now possible to obtain these values by indicating their index

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement