Array copies and references
Lesson 15 of 48 in Coddy's PHP for Rust Developers course.
Assigning a Rust Vec normally moves it; clone explicitly duplicates its elements according to their Clone implementations. PHP ordinary array assignment has value semantics without an ownership move. Nested Rc handles or PHP object identifiers can still retain shared state after an outer copy.
Ordinary PHP array assignment has value semantics, commonly implemented with copy-on-write. Changing a scalar element in the copy leaves the original array unchanged. Explicit references and object elements require separate reasoning: copying an array does not recursively clone objects stored inside it.
Rust program
fn main() {
let a=vec![1]; let mut b=a.clone(); b[0]=9; println!("{}",a[0]);
}
Source output:
1PHP program
demo.php
<?php
declare(strict_types=1);
$a=[2]; $b=$a; $b[0]=8; echo $a[0],":",$b[0],"\n";
PHP output:
2:8Challenge
EasyInput is a list of integers. replaceFirst returns a copy with its first value replaced by nine, if present. Input must remain unchanged. Driver prints original|copy, comma-separated.
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);
$a=[1,3];ensure(replaceFirst($a)===[9,3] && $a===[1,3],"copy");
echo implode(",",$input)."|".implode(",",replaceFirst($input)),"\n";
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PHP for Rust 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 batch3Collections
Lists are PHP arraysKeys, null and presenceArray copies and referencesFiltering and dense keysOrdering without mutationRecap: word countsPractice on your own: Online PHP compiler