0

I have a already defined array, containing values just like the one below:

$arr = ['a','b','c'];

How could one add the following using PHP?

$arr = [
   'a' => 10,
   'b' => 5,
   'c' => 21
]

I have tried: $arr['a'] = 10 but it throws the error: Undefined index: a

I am surely that I do a stupid mistake.. could someone open my eyes?

Full code below:

$finishes = []; //define array to hold finish types
foreach ($projectstages as $stage) {
    if ($stage->finish_type) {
        if(!in_array($stage->finish_type, $finishes)){
            array_push($finishes, $stage->finish_type); 
        }
    }
}

foreach ($projectunits as $unit) {
    $data[$i] = [
        'id' => $unit->id,
        'project_name' => $unit->project_name,
        'block_title' => $unit->block_title,
        'unit' => $unit->unit,
        'core' => $unit->core,
        'floor' => $unit->floor,
        'unit_type' => $unit->unit_type,
        'tenure_type' => $unit->tenure_type,
        'floors' => $unit->unit_floors,
        'weelchair' => $unit->weelchair,
        'dual_aspect' => $unit->dual_aspect
    ];  
    $st = array();    
    $bs = '';     
    foreach ($projectstages as $stage) {
        $projectmeasure = ProjectMeasure::select('measure')
                ->where('project_id',$this->projectId)
                ->where('build_stage_id', $stage->id)
                ->where('unit_id', $unit->id)
                ->where('block_id', $unit->block_id)
                ->where('build_stage_type_id', $stage->build_stage_type_id)
                ->first();

        $st += [
            'BST-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure : '0')
        ]; 
        
        if (($stage->is_square_meter == 0) && ($stage->is_draft == 0)) {
            $height = ($stage->height_override == 0 ? $unit->gross_floor_height : $stage->height_override); //08.14.20: override default height if build stage type has it's own custom height
            $st += [
                'BST-sqm-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure * $height: '0')
            ]; 
            if ($stage->finish_type) {
                $finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure * $height: '0') * ($stage->both_side ? 2 : 1); //error is thrown at this line
            }
        } else {
            if ($stage->finish_type) {
                $finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure : '0');
            }
        }

    }
    $data[$i] = array_merge($data[$i], $st);
    $data[$i] = array_merge($data[$i], $finishes[$stage->finish_type]);
    $i++;
}

The above code is used as is and the array $finishes is the one from the first example, called $arr

13
  • 5
    “I have tried: $arr['a'] = 10 but it throws the error: Undefined index: a - no it doesn’t: 3v4l.org/7koaV Commented Aug 14, 2020 at 8:43
  • it does, that's why I am here. And the downvote is just rude.. Commented Aug 14, 2020 at 8:43
  • 1
    Writing $arr['a'] = 10 doesn't add value to a that you initialized in the first place. a IS the value of first element in array. If you write a line of code that you said is throwing exception, you'll just add key 'a' with value '10' to array that consists of [0] => 'a', [1] => 'b', .... Commented Aug 14, 2020 at 8:48
  • 1
    You're using += in your real code instead of =. That tries to do maths to add to an existing value, whereas = can just assign the new index if it doesn't exist. It can't do maths to add a number to nothing. You need to check first if the index exists yet. If it doesn't exist, then assign it with an initial value. If it already exists with a value, then you can add the new value to the existing value. Commented Aug 14, 2020 at 8:51
  • 1
    P.Sthe downvote is purely practical, to show the question wasn't clear. You said "I have tried:$arr['a'] = 10" but when we see your real code, we learn that this isn't actually true at all. Details matter in programming. Commented Aug 14, 2020 at 8:54

2 Answers 2

1

You're using += in your real code instead of =. That tries to do maths to add to an existing value, whereas = can just assign a new index with that value if it doesn't exist.

+= can't do maths to add a number to nothing. You need to check first if the index exists yet. If it doesn't exist, then assign it with an initial value. If it already exists with a value, then you can add the new value to the existing value.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to convert the array of strings to a collection of keys (elements) and values (integers), you can try the following:

$arr = ['a','b','c'];
$newVals = [10, 5, 21];
function convertArr($arr, $newVals){
     if(count($arr) == count($newVals)){
          $len = count($arr);
          for($i = 0; $i < $len; $i++){
               $temp = $arr[$i];
               $arr[$temp] = $newVals[$i];
               unset($arr[$i]);
          }
     }
     return $arr;
}
print_r(convertArr($arr, $newVals));

Output:

Array ( [a] => 10 [b] => 5 [c] => 21 )

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.