Unable to set variable type in PHP
-
20-04-2021 - |
Question
Let's say I have an array like this:
$array = array ('1','2','3','4');
And I want to add parts of given string (even it consists of numbers) to the array if it isn't already exist in array. For example, if the given string is 1234
, it should add 12
, 23
and 34
. I wrote simple code for it like this:
$string = '1234';
$string_length = 4;
$array = array ('1','2','3','4');
for($i=0;$i<$string_length-1;$i++){
$element = substr($string,$i,2);
if (!in_array($element, $array)){
array_push($array, $element);
}
}
It works well when I try 1234
as $string
. But when I try 1024
as $string
, it returns the array like this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 10
[5] => 24
)
As you see, after [4] => 10
, there must be [5] => 02
, but there isn't it.
The cause is 02
is equal to 2
(which is in first given array) as a integer. That's why the code skipped it. But I need to add it.
For solving problem I set the type of $element
as a string
. So I added settype($element,'string');
after $string_length
in my code, but nothing changed.
What can I do ?
Solution
OTHER TIPS
Use the following code:
Notice I am passing true
to the in_array function. It does a strict comparison.
http://www.php.net/manual/en/function.in-array.php
$string = '1024';
$string_length = 4;
$array = array ('1','2','3','4');
for($i=0;$i<$string_length-1;$i++){
$element = substr($string,$i,2);
if (!in_array($element, $array, true)){
array_push($array, $element);
}
}