PHP Card Deck - PHP Online
Form of PHP Sandbox
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php
in the places where the PHP script should be executed.
Result of php executing
Full code of PHP Card Deck.php
- <?php class DeckOfCards {
- private $suits;
- private $ranks;
- public $deck;
- function __construct(){
- $this->suits = ["S","D","H","C"];
- $this->ranks = ["A",2,3,4,5,6,7,8,9,10,"J","Q","K"];
- foreach($this->suits as $s){
- foreach($this->ranks as $r){
- $this->deck[]="$r$s";
- }
- }
- }
- function show_deck() {
- // returns an array of all cards currently in the deck.
- return $this->deck;
- }
- function deal_one_card(){
- // deal one random card from the deck, then remove it.
- if(empty($this->deck)) return false; // no cards left
- $arrLen = count($this->deck);
- $key = mt_rand(0,$arrLen-1);
- $card = $this->deck[$key];
- array_splice($this->deck, $key,1);
- return $card;
- }
- function deal_top_card(){
- // deal the top card from the deck, then remove it.
- if(empty($this->deck)) return false; // no cards left
- array_splice($this->deck, 0, 1);
- return $card;
- }
- function shuffle(){
- // Shuffles all the cards currently in the deck.
- if(empty($this->deck)) return; // no cards in the deck to shuffle.
- $arrLen = count($this->deck);
- for($i=0; $i < $arrLen; $i++) {
- $newDeck[] = $this->deal_one_card();
- }
- $this->deck = $newDeck;
- }
- }
- $myCards = new DeckOfCards;
- //// TEST: Deal cards until deck is empty
- $myCards->shuffle();
- // 1.a. ensure the deck was shuffled properly:
- print_r($myCards->show_deck());
- // 1.b. deal cards until they are gone.
- // ( Iterate 53 times to ensure deal_one_card() properly returns false when the deck is empty. )
- for($i=1;$i<=53;$i++){
- $card = $myCards->deal_one_card();
- if($card) {
- echo "You were dealt " . $card ."<br>";
- }
- else {
- echo "There are no cards left";
- break;
- }
- }
- ?>
File Description
- PHP Card Deck
- PHP Code
- 22 Feb-2021
- 1.69 Kb
You can Share it:
Latest PHP Pastes