Jump to content

array_search()


drummer101

Recommended Posts

<?php
$fruit = array(
		1 => _('apple'),
		2=>('orange'),
		3=>('banana'),
		4=>('kiwi'),
		);?>

 

So my array key is being passed from a select box, given the numeric key, how can I search the array and match the key to the value?

 

array_search(3, $fruit) returns "Array"

I'm kinda new to php and arrays confuse me =\

 

Thanks for the help!

Link to comment
https://forums.phpfreaks.com/topic/98411-array_search/
Share on other sites

Thanks for the quick response ACE, however I'm looking for a function that does the opposite. Searches the array given a key, and returns the value.

 

array_search — Searches the array for a given value and returns the corresponding key if successful

 

And I don't see any related functions on that page.

 

Regards.

Link to comment
https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503657
Share on other sites

So there isn't a built in function that checks keys of the array and then returns the attached value to that key?

 

given

<?php<?php
$fruit = array(
		1 => ('apple'),
		2=>('orange'),
		3=>('banana'),
		4=>('kiwi'),
		);?>

I would need to write a function to check if key "4" exists, and return the value if true?

Link to comment
https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503664
Share on other sites

No but you can do this:

$fruit = array(
		1 =>('apple'),
		2=>('orange'),
		3=>('banana'),
		4=>('kiwi'),
		);

$key = 1;
if(array_key_exists($key, $fruit))
{
    echo $fruit[$key];
}

// alternative way:
if(isset($fruit[$key]))
{
    echo $fruit[$key];
}

Link to comment
https://forums.phpfreaks.com/topic/98411-array_search/#findComment-503668
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.