0

I'm trying to get two key values and add them both to a foreach. I can't seem to get it to work. Any help will be appreciated.

So I have an array that looks like this:

(
    [0] => Array
        (
            [Code1] => M22
            [Code2] => M33
            [Code3] => S44
        )
    [1] => Array
        (
            [Code1] => E22
            [Code2] => E33
            [Code3] => E44
        )
)

How can I search in the array and get the key and values for Code2 & Code3 and add both of them to a foraeach?

I can get the Code3 by doing this. This works for the last array element using "array_pop" but can't figure out how to get Code2.

// Filter and get the Code3
$pcodes = array_map('array_pop', $this->dpparent);
foreach ($pcodes as $parent_code) {
    echo "\r\n". $parent_code;
}
4
  • Can you explain "get" a little more? Also, have you tried just a double for loop?
    – Chris Haas
    Feb 3, 2021 at 18:07
  • Get as in get the value of both keys code2 and code3
    – Dan Kelly
    Feb 3, 2021 at 18:13
  • Have a look at array_column.
    – El_Vanja
    Feb 3, 2021 at 18:15
  • you can use foreach for every array and when find key return value and break the foreach .
    – bnnoor
    Feb 3, 2021 at 19:46

2 Answers 2

0

The simplest way is probably a double for loop:

foreach ($data as $subarray) {
    foreach ($subarray as $key => $value) {
        if (in_array($key, ['Code2', 'Code3'], true)) {
            // Logic here
        }
    }
}
0

If you know the name of the keys, then you can use array_column to extract the values:

$code2values = array_column($data, 'Code2');
$code3values = array_column($data, 'Code3');
foreach ($code2values as $key => $code2) {
    $code3 = $code3values[$key];
    // do something with $code2 and $code3
    echo "code2: $code2, code3: $code3\n";
}

Output (for your sample data):

code2: M33, code3: S44
code2: E33, code3: E44

Demo on 3v4l.org

Your Answer

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

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