tags:

views:

65

answers:

2

Is there any way I can search an array for a value and return it's key, I tried array_search() with no success... below is an example of my array

[0] => Array
    (
        [value] => 
        [text] => All Call Types
    )

[1] => Array
    (
        [value] => enquiry
        [text] => Renovation Enquiry
    )

[2] => Array
    (
        [value] => msg
        [text] => Message to Pass on
    ) ...

My ultimate goal is to convert

value to text.

Here's what I tried:

$key = array_search($row['call_type'], $type_list);
$call_type_name = $type_list[$key]['text'];

Thanks!

+2  A: 

You could write a short function that provides this:

function findInArray($array, $needle)
{
    for ($i = 0; $i < sizeof($array); $i++)
    {
        if ($array[$i]['value'] == $needle) return $array[$i]['text'];
    }
}

Usage example:

$call_type_name = findInArray($type_list, 'msg');
JYelton
Obviously this function may be better named `getCallTypeName` or something to your liking.
JYelton
Wow I'm surprised the search_array() function doesn't do this.. I pretty new to php--so what's it's purpose then? BTW, I'll try you solution after lunch. ;)
Mikey1980
From the manual page (http://php.net/manual/en/function.array-search.php) `array_search()` Searches the array for a given value and returns the corresponding key if successful. In your example, you have an array of arrays (multi-dimensional array). `array_search()` is only checking the first dimension, and not finding an element matching `$row['call_type']` -- instead it is finding arrays. If your array were constructed differently, as an associative array with strings as the call type, and the key itself used for the 'value' you could just return `$type_list[$key]` and not need to search.
JYelton
+1  A: 

is this what you are after? finding the position of the occurrence of a specific value?

function findKeyByField( $arr, $name, $val ){
$pos = 0;
foreach ($arr as $subArr ):

    foreach ($subArr as $key => $value):
        if( $key == $name and $value == $val ){
            return $pos;
        }
    endforeach;

$pos++;
endforeach;
}
David Morrow
I shake everytime I see that syntax :p
Artefacto
what syntax is that, nested foreach? whats the better way, please, i learn something new everyday, what would be better.
David Morrow
you rock, despite the shaking it made into to my public class :)
Mikey1980
$key=Misc::findKeyByField($type_list, 'value', $row['call_type']);$call_type_name = $type_list[$key]['text'];
Mikey1980