Skip to content
Advertisement

Why can’t I add a key and value when PHP array_key_exists is FALSE?

I am simply trying to add a set of keys and values to an array if and only if they are not already in the array. I need to add d1 thru d20 when they are not already in the array,

Here is my code.

print_r($demos_keys)

Array
(
    [0] => d01
    [1] => firstname
    [2] => lastname
    [3] => email
    [4] => d02
    [5] => d03
    [6] => partnerid
)
$counter=0;
foreach ($csvdata as $row) {
    if ($counter > 0) {
    $rowdata_tmp = explode(',', trim($row));
    $rowdata_tmp['partnerid'] = $partnerid;
    $rowdata[] = array_combine($demos_keys, $rowdata_tmp);


//Fails to add 'd04'
        // if(isset($rowdata['d04'])){
        // $x=1;
        // } else {
            // $rowdata['d04']='';
        // }

//Fails to add 'd04'
        // if(isset($rowdata['d04'])){
        // $x=1;
        // } else {
            // $row['d04']='';
        // }
        
//Fails 
    if (array_key_exists('d04',$rowdata)==FALSE) {$rowdata['d04'] = '';}
    }

//Fails 
    if (array_key_exists('d04',$rowdata)==FALSE) {$row['d04'] = '';}
    }


    $counter = $counter + 1;
    
}

print_r($rowdata);

Array
(
    [0] => Array
        (
            [d01] => 1
            [firstname] => Fred
            [lastname] => Dryer
            [email] => FredDryer1@email.com
            [d02] => Backfield
            [d03] => North
            [partnerid] => 14
        )

I CAN add d04 by inserting $rowdata_tmp[‘d04’] = ”; before the array_combine statement, but the problem is that d04 will sometimes already be present in demos_keys.

Can someone help? I’m dying here.

Advertisement

Answer

You’re checking for the key in the top-level $rowdata array, not the new row that you’re adding to the array.

$rowdata_tmp = explode(',', trim($row));
$rowdata_tmp[] = $partnerid;
$new_row = array_combine($demos_keys, $rowdata_tmp);
if (isset($new_row['d04'])) {
    $x = 1;
} else {
    $new_row['d04'] = '';
}
$rowdata[] = $new_row;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement