PHP code example of jmbg-labs / jmbg

1. Go to this page and download the library: Download jmbg-labs/jmbg library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jmbg-labs / jmbg example snippets


use JmbgLabs\Jmbg\Jmbg;

// Quick validation
if (Jmbg::valid('0101000710009')) {
    echo "Valid JMBG";
}

// Parse and validate
try {
    $jmbg = Jmbg::parse('0101000710009');
    echo "Valid JMBG: " . $jmbg->format();
} catch (JmbgException $e) {
    echo "Invalid JMBG: " . $e->getMessage();
}

use JmbgLabs\Jmbg\Jmbg;

$jmbg = new Jmbg('0101000710009');

// Get birth date
$date = $jmbg->getDate(); // DateTime object
echo $date->format('Y-m-d'); // 2000-01-01

// Get age
echo $jmbg->getAge(); // e.g., 26

// Check gender
if ($jmbg->isMale()) {
    echo "Male";
}

if ($jmbg->isFemale()) {
    echo "Female";
}

// Access individual parts
echo $jmbg->day;           // 1
echo $jmbg->month;         // 1
echo $jmbg->year;          // 2000
echo $jmbg->region;        // 71
echo $jmbg->region_text;   // "Belgrade"
echo $jmbg->country;       // "Serbia"
echo $jmbg->unique;        // 0
echo $jmbg->checksum;      // 9

$jmbg = new Jmbg('1505995800002');

// String conversion
echo (string)$jmbg; // "1505995800002"
echo $jmbg->format(); // "1505995800002"

// Property access
echo $jmbg->original;        // "1505995800002"
echo $jmbg->day_original;    // "15"
echo $jmbg->month_original;  // "05"
echo $jmbg->year_original;   // "995"
echo $jmbg->region_original; // "80"
echo $jmbg->unique_original; // "000"

// Check property existence
if (isset($jmbg->region_text)) {
    echo $jmbg->region_text; // "Novi Sad"
}

$jmbgs = ['0710003730015', '1705978730032', 'invalid'];

foreach ($jmbgs as $jmbgString) {
    if (Jmbg::valid($jmbgString)) {
        $jmbg = Jmbg::parse($jmbgString);
        echo sprintf(
            "%s - Born: %s, Region: %s, Gender: %s\n",
            $jmbg->format(),
            $jmbg->getDate()->format('Y-m-d'),
            $jmbg->region_text,
            $jmbg->isMale() ? 'Male' : 'Female'
        );
    } else {
        echo "$jmbgString - Invalid\n";
    }
}

$jmbg = new Jmbg('0710003730015');
$age = $jmbg->getAge();

if ($age >= 18) {
    echo "Adult";
} else {
    echo "Minor";
}

use JmbgLabs\Jmbg\Jmbg;
use JmbgLabs\Jmbg\JmbgException;

try {
    $jmbg = new Jmbg('1234567890123');
} catch (JmbgException $e) {
    // Handle specific validation errors
    echo "Validation failed: " . $e->getMessage();
    // Possible messages:
    // - "Input string must have 13 digits."
    // - "JMBG string must have 13 digits."
    // - "Date '...' is not valid."
    // - "Region '...' is not valid for Serbian JMBG."
    // - "Checksum is not valid."
}