Jump to content

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

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.