0

I have this the values of in my array as

$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);

If the user enter the value item3 he has to get 70 which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.

4
  • "I tried alot" -- what precisely have you tried? Commented Aug 30, 2013 at 10:53
  • Don't just tell us that you tried using explode, show how you tried to do it. Commented Aug 30, 2013 at 10:53
  • 1
    And are these strings? array("item1-0-100", "item2-0-50", ...) or is one of the parts a key? Commented Aug 30, 2013 at 10:53
  • What does your code look like at the moment? If you post what you are using, we can probably look at it and see what the problem is. As it stands, someone has to write a completely new bit of code. Commented Aug 30, 2013 at 10:54

3 Answers 3

5

Try with:

$itsthere = array(
  'item1-0-100',
  'item2-0-50',
  'item3-0-70',
  'item4-0-50',
  'item5-0-100'
);

$search = 'item3';
$output = '';

foreach ( $itsthere as $value ) {
  if ( strpos($search . '-', $value) === 0 ) {
    $output = explode('-', $value)[2];
    break;
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You have a typo @strpos($seach ...
What if the user needs to do this over and over again? There's a much better way
@GeorgeJempty Suggest something then. :-)
1

When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key

$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.

If you only want to know if this key is in the array use array_key_exists.

Comments

-1

Try this :

    $item = 'item3';
    $itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');

    foreach($itsthere as $there)
    {
        $exp = explode('-',$there);
        if($exp[0] == 'item3') {
            echo $val = $exp[2];
        };
    }

9 Comments

There are two ways to improve performace - break after found result and strpos before unnecessary explode - as in my answer.
break barely improves performance, it's still O-n in algorithm speak. If you want to improve performance, iterate (O-n) the array once and create a lookup table, instead of O-n performance every single time.
@GeorgeJempty ok next time i will doing like this.
whats wrong in this george, i use break; after echo $val = $exp[2];
@GeorgeJempty why you remove answer ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.