Keys and iteration
Lesson 11 of 48 in Coddy's PHP for C# Developers course.
C# foreach receives elements of an enumerable; dictionary entries are key-value values, not PHP key => value syntax. The source uses an ordered pair array to make order explicit. PHP arrays preserve insertion order and foreach can expose both key and value.
foreach($items as $key => $value) exposes array keys directly. A normal value iteration does not assign back through the loop variable. By-reference iteration using &$value behaves differently and leaves a reference behind; unset it after such a loop. Prefer ordinary iteration unless mutation is intentional.
C# program
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main() {
var pairs=new[]{new KeyValuePair<string,int>("x",4),new KeyValuePair<string,int>("y",7)};foreach(var pair in pairs)Console.WriteLine(pair.Key+pair.Value);
}
}Source output:
x4
y7PHP program
demo.php
<?php
declare(strict_types=1);
$a=["x"=>4,"y"=>7]; foreach($a as $k=>$v){echo $k,$v,"\n";}
PHP output:
x4
y7Challenge
EasyInput is a list of integers -100..100. weighted sums each value times its zero-based index. Do not change the input.
The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.
Edit Functions.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.
Try it yourself
<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(weighted([8,2,5])===12,"weighted");
echo (string)weighted($input),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for C# Developers
1Values and output
Modules and first runFormatting returned textAssignments and variablesDivision and conversionStrings and byte lengthsExplicit Boolean rulesRecap: receipt text4Functions and modules
Functions and return typesDefaults and named callsVariadic argumentsCallbacks and capturesrequire_once and scopeRecap: integer cents2Control flow
Branches and precedenceStrict match expressionsLoops and early exitsKeys and iterationRecap: shipping rules5Errors and boundaries
Exceptions and stateStrict input validationNull is not falsyRecap: validate a batchPractice on your own: Online PHP compiler