1

My database outputs a list of topics, but array_column() casts the numeric strings to integers, so my array is no more consistent:

$list = [
    [
        'k' => '1967', 
        'v' => '1967 v',
    ],
    [
        'k' => '1939-1945', 
        'v' => '1939-1945 v',
    ],
];

$list = array_column($list, 'v', 'k');
$result = [];
foreach ($list as $k => $v) {
    $result[] = [$k => gettype($k), $v => gettype($v)];
}
print_r($result);

So the result is:

Array
(
    [0] => Array
        (
            [1967] => integer
            [1967 v] => string
        )
    [1] => Array
        (
            [1939-1945] => string
            [1939-1945 v] => string
        )
)

How to avoid the automatic casting of the string "1967" in a simple way?

Daniel-KM
  • 174
  • 1
  • 1
  • 13
  • Use of ```strval()``` is not working: `$list = array_combine(array_map('strval', array_keys($list)), array_values($list)); ` – Daniel-KM Jun 12 '21 at 06:39
  • How does this actually cause a problem? – Nigel Ren Jun 12 '21 at 06:47
  • Of course, the automatic casting is related to the language: https://www.php.net/manual/en/language.types.array.php . – Daniel-KM Jun 12 '21 at 06:49
  • @NigelRen I use other functions after, like `array_merge()` or functions with types `function(string $k, string $v)` and they don't work. – Daniel-KM Jun 12 '21 at 06:50
  • It's actually more fundamentally part of php - https://stackoverflow.com/questions/4100488/a-numeric-string-as-array-key-in-php. So if you try `$list = ['1967' => '1967 v'];` you will still get an integer as the key. – Nigel Ren Jun 12 '21 at 07:03
  • @NigelRen Thanks, this is the same issue. And this answer https://stackoverflow.com/a/35180513/7103991 is working: `$list = (object) $list;`, where "1967" is a string! Not sure of performance, but it is another point. – Daniel-KM Jun 12 '21 at 07:14
  • If that has solved the problem, then can I close this question as a duplicate? – Nigel Ren Jun 12 '21 at 07:15
  • That sounds potentially misleading. Others may miss that space and spend some time wondering why they can't find the data they are after. Your decision, just wanted to point out a potential issue. – Nigel Ren Jun 12 '21 at 07:26
  • @NigelRen Yes, my solution is related to my code, it may not work in more generic cases. – Daniel-KM Jun 12 '21 at 07:32

1 Answers1

0

I prefer to use foreach and create customizable results.

$results = [];
foreach($list as $key=>$value){
    // do somethings
Hamid
  • 356
  • 2
  • 10
  • The issue is about `array_column()`, the `result` is just to see issue. In some cases, the list is used for `array_merge` or a function that requires strings. – Daniel-KM Jun 12 '21 at 06:54