user3817533
user3817533

Reputation: 659

PHP foreach/else issue

foreach($cases['rows'] as $i => $item) {
    foreach($array as $key => $val) {
        if($item['status'] == $key) {
            echo $val;
        }
    }
}

Right now this code functions, but if $item['status'] != $key it echoes nothing. I've tried to add an else statement after the if statement except it prints it tens of times.

How can I achieve this functionality? I want it to print $item['status'] if $item['status'] != $key

Help is appreciated.

Thanks.

Upvotes: 0

Views: 16309

Answers (3)

chrisp
chrisp

Reputation: 629

The way I understand the question you have two arrays:

  1. An array containing different abbreviations and their full meaning.
  2. Another multidimensional array containing arrays which again contain status-abbreviations.

To echo the full meaning instead of the abbreviations:

$abbreviations = array('NT' => 'Not taken',
                       'N/A' => 'Not available');

$data = array(array('status' => 'NT'),
              array('status' => 'N/A'));

foreach($data as $item) {
    if(array_key_exists($item['status'], $abbreviations)) {
        echo $abbreviations[$item['status']] . PHP_EOL;
    } else {
        echo $item['status'] . PHP_EOL;
    }
}

Result:

Not taken

Not available

Upvotes: 2

jfloff
jfloff

Reputation: 118

Without more info regarding the type of data in both arrays, I would suggest you to try:

  • !($item['status'] == $key) deny the correct statement
  • $item['status'] !== $key try also checking the same type (test this also with the equal statement to see if you get the results you expect)

Upvotes: 0

Sebastien
Sebastien

Reputation: 1328

Try this:

$test = null;
foreach($cases['rows'] as $i => $item) {
    foreach($array as $key => $val) {
        if($item['status'] == $key) {
            echo $val;
        }
        else {
            $test = $val;
        }
    }
}
if($test != null) {
    echo $test//Or whatever you want to display
}

Upvotes: 1

Related Questions