Jump to content

[SOLVED] array search


iversonm

Recommended Posts

so far i have

$array = array(0 => array('blue', 1), 1 => array('red', 2), 2 => array('green', 3), 3 => array('red', 4));

$key = array_search('green', $array); // i want $key=2
echo $key;//should echo 2 but it echos nothing 

 

how do i get this to work,

Link to comment
Share on other sites

That's because you have a multidimensional array. Just create a custom search function since you are using a custom array

 

function search_myarray($search_val, $input_array)
{
    $return_val = false;

    foreach($input_array as $key => $sub_array)
    {
        if ($sub_array[0]==$search_val)
        {
            $return_val = $key;
            break;
        }
    }
    return $return_val;
}

$array = array(
0 => array('blue', 1),
1 => array('red', 2),
2 => array('green', 3),
3 => array('red', 4)
);

$key = search_myarray('green', $array);
echo $key; //Will echo 2

 

 

Link to comment
Share on other sites

hrm.... let see if i had to scale how well that worked from 1 to 10 it would most definaitly be a 12 so i thank you, it does exactly what i want it to

 

thankyou mjdamato

 

topic solved, im sure you all will you will all see me again

Link to comment
Share on other sites

I would add...

 

There might be a reason why you are contructing your array in that manner, but unless the the key of the first array value and the numeric value in the secondary array are unique values that you really need (e.g. 2 & 3 for green), I would suggest creating your array like this:

$array = array(
1 => 'blue',
2 => 'red',
3 => 'green',
4 => 'red'
);

Link to comment
Share on other sites

well i just added the numbers in to show that it was array inside an array and if the second array only had 1 object then it would be pointless to have a second array but inside each second array is about 50 variables that all need to be accounted for sooo i couldn't just use array array_multisort like before but thanks for the input

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.