user3556802 user3556802 - 5 months ago 9
PHP Question

how to assign id based on array values

I am learning php please help.

I am storing values in an array and then I am trying to get the id of another array checking the value in array like this:

$arr_folders = ['one', 'two', 'whatever'];

$id_one = '';
$id_two = '';
$id_whatever = '';
foreach ($tree as $key => $value) {
if($value['name'] == 'one'){//how to check dynamically?
$id_one = $value['id'];
}
if($value['name'] == 'two'){//how to check dynamically?
$id_two = $value['id'];
}
if($value['name'] == 'whatever'){//how to check dynamically?
$id_whatever = $value['id'];
}
}
echo $id_whatever;


How can I check the arrays values dynamically. I mean I want to check if the value exist in array then assign their id.

Answer

You need to use in_array to check whether the element is exist or not in another array, and if found you can create dynamic variable based on $value['name'] containing $value['id'] as required.

$tree = [
    ['id' => 1, 'name' => 'one'],
    ['id' => 2, 'name' => 'two'],
    ['id' => 3, 'name' => 'three']
];
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
    if (in_array($value['name'], $arr_folders)) {
        ${'id_'.$value['name']} = $value['id'];
    }
}
echo $id_one;

Working Example: https://eval.in/596034

Note: make sure $value['name'] doesn't contain spaces or any other characters which aren't allowed to declare variable names.

Comments