0

I am trying to check if a value is in an array. If so, grab that array value and do something with it. How would this be done?

Here's an example of what I'm trying to do:

$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");

if (in_array('20', $the_array)) {

    // If found, assign this value to a string, like $found = 'jueofi31->20'

    $found_parts = explode('->', $found);

    echo $found_parts['0']; // This would echo "jueofi31"    

}
2
  • if your array is built like so: "buejcxut->10" it will be more complicated. The array should be like: "buejcxut"=>10 Commented Mar 26, 2012 at 13:16
  • in_array only provide the true or false according to the searched result, you need a different logic to get the searched value. Try the array_walk() and in_array together. Commented Mar 26, 2012 at 13:17

4 Answers 4

2

This should do it:

foreach($the_array as $key => $value) {
    if(preg_match("#20#", $value)) {
        $found_parts = explode('->', $value);
    }
    echo $found_parts[0];
}

And replace "20" by any value you want.

Sign up to request clarification or add additional context in comments.

Comments

1

you might be better off checking it in a foreach loop:

foreach ($the_array as $key => $value) {
  if ($value == 20) {
    // do something
  }
  if ($value == 30) {
    //do something else
  }
}

also you array definitition is strange, did you mean to have:

$the_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);

using the array above the $key is the element key (buejcxut, jueofi31, etc) and $value is the value of that element (10, 20, etc).

Comments

1

Here's an example of how you can search the values of arrays with Regular Expressions.

<?php

$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");

$items = preg_grep('/20$/', $the_array);

if( isset($items[1]) ) {

    // If found, assign this value to a string, like $found = 'jueofi31->20'

    $found_parts = explode('->', $items[1]);

    echo $found_parts['0']; // This would echo "jueofi31"    

}

You can see a demo here: http://codepad.org/XClsw0UI

Comments

0

if you want to define an indexed array it should be like this:

$my_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);

then you can use in_array

if (in_array("10", $my_array)) {
    echo "10 is in the array"; 
    // do something
}

Comments

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.