1

Is it possible that I can get the data from the other array based on the value from another?

If I input value from array it will return a value from other array.

Example:

$arr1 = ['A','B','C'];
$arr2 = [1,2,3,];

Input: 2
Result: B

0

4 Answers 4

5

Do they need to be separate?

You could use array_combine() to assign a key to the value and then input is just $array[$input] - e.g.

$arr1 = ['A', 'B', 'C'];
$arr2 = [1, 2, 3];

$arr = array_combine($arr2, $arr1);

echo $arr[$_POST['input']]; # will display 2
Sign up to request clarification or add additional context in comments.

5 Comments

Ohh, neat. Didn't think of array_combine().
@Qirel and I didn't think of array_search() xD haha :p
They have an interesting oposite though: array_search() will return the first instance of the result (in this case, 2), while array_combine() will return the last. So the two approaches will give different results if there are duplicate values in $arr2, as seen here: 3v4l.org/BZg0e
We just did ;-) But yeah, sure - if you want to edit in a note in your answer, knock yourself out (don't actually knock yourself out, that hurts - or so I've been told).
@Qirel xD nah, I mean, I guess it's more of a friendly just in-case then a requirement (as $arr1 = unique values).. so I guess comment will do :) and that's true, though, if knocked out quick enough, you skip the pain phase xD
3

Since your arrays have not been given any specific keys, they are assigned numerically indexes from PHP, starting from zero.

You can then use array_search() to get the key of the $arr2 array, and use that to find the value in $arr1.

$key = array_search($input, $arr2);
$output = $arr1[$key];

If either array has defined indexes, you can use array_values() to just get the values and get the numeric indexes from PHP again.

Comments

-1

This function combine 2 or more arrays

<?php
$array1 = array('A', 'B', 'C');
$array2 = array('1', '2', '3');

$result = array_merge($array1, $array2);

print_r($result);
?>

1 Comment

SHow us how can one use it. How will you get "B" for argument 2?
-1

Working with array $result above (1 of 2 possibility)

<?php echo $result[1]; ?>

Or use

<?php
$q = '2'; $key = array_search($q, $result);

if(!$key)
    echo "This search returned no key and value pair";
else
    echo "This search for value: " . $q . " is present in key: " . $key;
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.