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"    

}
link|improve this question

if your array is built like so: "buejcxut->10" it will be more complicated. The array should be like: "buejcxut"=>10 – w0rldart Mar 26 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. – punit Mar 26 at 13:17
feedback

4 Answers

up vote 1 down vote accepted

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.

link|improve this answer
feedback

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

link|improve this answer
feedback

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
}
link|improve this answer
feedback

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).

link|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.