'How do I define an associate multidimensional array inside a function And make the indexs(small arrays) in this array a parameter within the function [closed]

I want to define an association multidimensional array inside a function And make the indexs(small arrays) in this array a parameter within the function but also I want to restrict the data type(int,float,string) for these indexes

that's mean The user is not allowed to enter another data type in function parameter when called



Solution 1:[1]

I would do something like this:

<?php


/**
 * Print some data for a given index.
 * 
 * @param $index The index should be an int, a float or a string.
 * @throws TypeError when the index is in the bad type.
 * @throws OutOfRangeException when the index doesn't exist in the data array.
 */
function print_data($index) {
    static $data = [
        0 => 'element with int index',
        1.5 => 'element with float index',
        'firstname' => 'James',
    ];
    
    if (!is_numeric($index) && !is_string($index)) {
        throw new TypeError('The given index is not in the valid type!');
    }
    
    if (!isset($data[$index])) {
        throw new OutOfRangeException('The given index does not exist in the data!');
    }
    
    print "Value of index $index is: $data[$index]" . PHP_EOL;
}

$index_tests = [
    0,
    1.5,
    'firstname',
    true,           // Wrong index type.
    -2,             // Correct type but missing index.
    'lastname',     // Correct type but missing index.
    ['An array'],   // Wrong index type.
    new DateTime(), // Wrong index type.
];

foreach ($index_tests as $index) {
    try {
        print_data($index);
    }
    catch (TypeError | OutOfRangeException $e) {
        print 'Error with ' . var_export($index, true) . ': ' . $e->getMessage() . PHP_EOL;
    }
}

?>

It will output the following:

Value of index 0 is: element with int index
Value of index 1.5 is: element with float index
Value of index firstname is: James
Error with true: The given index is not in the valid type!
Error with -2: The given index does not exist in the data!
Error with 'lastname': The given index does not exist in the data!
Error with array (
  0 => 'An array',
): The given index is not in the valid type!
Error with DateTime::__set_state(array(
   'date' => '2022-04-21 07:53:54.087321',
   'timezone_type' => 3,
   'timezone' => 'UTC',
)): The given index is not in the valid type!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1