Lowder Lowder - 4 years ago 94
PHP Question

PHP get letter id from array

I have a array:

$arr = array(c,b,a);


And another array:

$string = array(a,a,b);


How to do to it give me a array looks like there:

$arr2 = array(2,2,1);


Sorry for my bad English.

Answer Source

Using array_search() could solve the problem, but remember array_search() will return FALSE if it does not find the value in the array

$arr = array('c','b','a');
$string = array('a','a','b');
$new_arr = array();

foreach ( $string as $value){
    $index = array_search($value, $arr);
    if ( $index !== false ) {
        $new_arr[] = $index;
    } else {
        $new_arr[] = -1;    // used -1 to indicate a NO FIND
    }
}

print_r($new_arr);

Result

Array
(
    [0] => 2
    [1] => 2
    [2] => 1
)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download