bhylu.com

Advertisements

PHP Voting Project

Model a small poll that asks which tool should be repaired next. Begin with a pure counting contract before adding any browser or persistence layer.

Your brief

The allowed choices are fixed server-side identifiers, while each vote increments one matching counter. This fixture does not enforce one vote per person, collect personal data or provide a public voting endpoint. A real poll must decide abuse limits, identity/privacy, idempotency, CSRF where applicable and shared-storage consistency. Keeping that boundary honest prevents a correct array update from being mistaken for a complete survey service.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l poll-project.php
php poll-project.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Worked solution

Show the worked solution
PHP 8.2+ · poll-project.php

<?php
declare(strict_types=1);

function recordVote(array $counts,string $choice): array {
    if (!array_key_exists($choice,$counts)) throw new InvalidArgumentException("Unknown choice");
    $counts[$choice]++;
    return $counts;
}
$counts = ["drill"=>0,"rake"=>0];
$counts = recordVote($counts,"drill");
$counts = recordVote($counts,"rake");
$counts = recordVote($counts,"drill");
echo json_encode($counts,JSON_THROW_ON_ERROR), "\n";
if ($counts !== ["drill"=>2,"rake"=>1]) throw new RuntimeException("Wrong tally");

Expected result

{"drill":2,"rake":1}

The sequence contains two drill votes and one rake vote. The exact-map assertion checks both counters. An unknown choice throws instead of silently creating a new privileged option. The array is returned explicitly so callers can see who owns the changed value.

Extend and test

Add a transaction-backed implementation with a separate policy for duplicate submissions.

Check the official PHP manual for detailed version and API contracts.