Home > Mobile >  How to get value from constant file array based on key in php?
How to get value from constant file array based on key in php?

Time:02-10

I have one file which is constants inside this file i have one array i want to call that array key into another file,can you please help me to fix the issue..?

constants.php

<?php


namespace App\Ship\Constants;


class Constants
{
    const USER_DEPT = 'MECH';
    const STAFF_DEPT = 'Batch_1';
    const USER_SECTION = 1;
    const STAFF_SECTION =50;

    
    const USER_TYPES = [
            self::USER_DEPT => self::USER_SECTION,
            self::STAFF_DEPT => self::STAFF_SECTION
    ];
}

Controller.php

//$field is either USER or STAFF based on request it's coming
public function check($field){ 
            constants::USER_TYPES[$field.'_DEPT'];
}

Error undefined index USER_DEPT

CodePudding user response:

When you declare an array key as variable then the actual key will be the assigned by the value of that variable. in your case USER_TYPES array contain these data:

Array
(
    [MECH] => 1
    [Batch_1] => 50
)

Thats why you getting undefined index error

if want to access array index like USER_DEPT then you have to assign your constant like this:

const USER_DEPT = 'USER_DEPT';
const STAFF_DEPT = 'STAFF_DEPT';

Or change array key like:

const USER_TYPES = [
    'USER_DEPT' => self::USER_SECTION,
    'STAFF_DEPT' => self::STAFF_SECTION
];
  • Related