Arrays value isset?

I have

echo '<pre>';print_r($unknownArray);echo '</pre>';

results in

Array
(
    [0] => Array
        (
            [name] => 
            [unknown_id] => 1
            [manufacturer] => fmnk
            [model] => hjnkhjk
            [chassis_id] => 1
            [rack_id] => 
        )

    [1] => Array
        (
            [name] => 
            [unknown_id] => 2
            [manufacturer] => fmnk
            [model] => hjnkhjk
            [chassis_id] => 1
            [rack_id] => 
        )

)

then im confused as to why

			if (isset($unknownArray['chassis_id'])) {
				$type = "rack";
			} else {
				$type = "chassis";
			}

seems to rresult in $type = chassis? if the key is set, shouldnt the if be true?

Try adding these lines after the array has been populated:

echo '<pre>'; 
  echo '$unknownArray ==> '; print_r($unknownArray);
  echo '<br> ... <br>';

  echo '$unknownArray[0] ==> '; print_r($unknownArray[0]); 
  echo '<br> ... <br>';

  echo '$unknownArray[1] ==> '; print_r($unknownArray[1]); 
echo '</pre>';  

Your array has two entries and they have the index 0 and 1. There is no entry with index “chassis_id”.
You can test on chassis_id only if you access the entries of your root array by

$unknownArray[0]['chassis_id'] 
or 
$unknownArray[1]['chassis_id'] 
1 Like

Agreed, you will need to loop through the array and assign the type to each sub array.

foreach($unknownArray as $k => $arr):
	$unknownArray[$k]['type'] = (!empty($unknownArray[$k]['chassis_id']) ? "rack" : "chassis"); 
endforeach;

echo "<pre>";
print_r($unknownArray);	
echo "</pre>";

Added a few array items for test. Results show as this.

Array
(
    [0] => Array
        (
            [name] => 
            [unknown_id] => 1
            [manufacturer] => fmnk
            [model] => hjnkhjk
            [chassis_id] => 1
            [rack_id] => 
            [type] => rack
        )

    [1] => Array
        (
            [name] => 
            [unknown_id] => 2
            [manufacturer] => fmnk
            [model] => hjnkhjk
            [chassis_id] => 1
            [rack_id] => 
            [type] => rack
        )

    [2] => Array
        (
            [name] => 
            [unknown_id] => 3
            [manufacturer] => fmnk
            [model] => hjnkhjk
            [chassis_id] => 
            [rack_id] => 
            [type] => chassis
        )

    [3] => Array
        (
            [name] => 
            [unknown_id] => 4
            [manufacturer] => fmnk
            [model] => hjnkhjk
            [chassis_id] => 
            [rack_id] => 
            [type] => chassis
        )

)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.