Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_combine php function doesn't preserve data type of string variable if the variable is int value

Tags:

arrays

php

array_combine php function doesn't preserve data type of string variable if the variable is int value

A simple example :

$a = array('1', '2');
$b = array('first', 'second');
$c = array_combine($a, $b);
$ak = array_keys($c);
var_dump($ak);

This will produce output as : integer values of 1 and 2.

What i wanted is to preserve string type of values 1 and 2

for temporary, i have used :

array_walk to to eventually achieve what i want.

like image 537
jospratik Avatar asked Jul 20 '26 16:07

jospratik


1 Answers

This is not because specific behavior of array_combine() function, but because of valid-integer keys type-casting in PHP arrays:

$array = [1=>'foo', '2'=>'bar', 'x'=>'baz'];
var_dump($array); // 1 and 2 are int

There are also some other rules with keys type-casting (see link above).

However, there are some tricks to achieve string keys anyway, like:

$obj = new StdClass();
$obj->{'1'}='foo';
var_dump((array)$obj);//array(1) { ["1"]=> string(3) "foo" } 

-but that is only for information - I would not recommend to use that. For your question, you can use something like array_map() applying it to result of array_keys() - but that will not save you - you'll not be able to determine which key was integer and which was string.

like image 155
Alma Do Avatar answered Jul 22 '26 06:07

Alma Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!