user3905044
user3905044

Reputation: 77

PHP Array Push String But Missing Zeros

Here is my code:

<?php
$num = array("00000001","1","00001232","2","13454234","3");

$longnum = array();
$shortnum = array();

foreach($num as $key => $value)
{
    if($key % 2 == 0)
    {
        $longnum[] += $value;
    }
    else
    {
        $shortnum[] += $value;
    }
}

Expected output:

Long num: Array ( [0] => 00000001 [1] => 00001232 [2] => 13454234 )
Short num: Array ( [0] => 1 [1] => 2 [2] => 3 ) 

But my output:

Long num: Array ( [0] => 1 [1] => 1232 [2] => 13454234 ) 
Short num: Array ( [0] => 1 [1] => 2 [2] => 3 )

I want to get the long num same as the expected output. However, my output doesn't included the zero inside an array. How should I do?

Upvotes: 0

Views: 260

Answers (3)

Fluffeh
Fluffeh

Reputation: 33532

The code you have in your question uses PHPs ability to typecast automatically. When you try to do math operations on strings, PHP is kind enough to try to convert them to numbers on your behalf.

By using a += operator, you are forcing PHP to do this as you append to an array.

foreach($num as $key => $value)
{
    if($key % 2 == 0)
    {
        $longnum[] = $value;
    }
    else
    {
        $shortnum[] = $value;
    }
}

By changing your code to this, you will get the expected results.

Additionally, by using [] you are automatically adding a new element to an array - so a += would actually be pointless - there is no value to add to - unless you were doing it specifically to force PHP typecasting to a number, in which case, there would be better ways to do it.

Upvotes: 1

bansi
bansi

Reputation: 57052

You should Type Cast value or it will be treated as int by intelligent guess.

$longnum[] = (string)$value;

Quote from manual:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

Upvotes: 1

MH2K9
MH2K9

Reputation: 12039

You should just assign(=) to array. Remove += instead. Try this

$num = array("00000001","1","00001232","2","13454234","3");

$longnum = array();
$shortnum = array();

foreach($num as $key => $value)
{
    if($key % 2 == 0)
    {
         $longnum[] = $value;
    }
    else
    {
        $shortnum[] = $value;
    }
}

Upvotes: 0

Related Questions