user1074330
user1074330

Reputation: 21

PHP Copy value to a new 2d array, first digit keeps being replaced with "0"

$count = count($itemArray);

// Create a new array slot to store the item #
$itemArray[$count] = $matches[1][$i];
$itemArray[$count][0] = 0;

This is part of a loop ($i is the index). Everytime this part of the loop occurs, the number is successfully copies from $matches array to the $itemArray except the first digit of the entire number is replaced with a 0 every time. I'm sort of new to 2d arrays in php so I'm guessing the problems might lie within the 2d syntax.

Examples of what the values end up being (they should be the same)

$matches[1][$i] = 250924377376
$itemArray[$count] = 050924377376

Upvotes: 0

Views: 383

Answers (1)

drew010
drew010

Reputation: 69967

You are not actually creating a 2-d array.

You have $itemArray which is an array.

When you do $itemArray[$count] = $matches[1][$i]; you are setting $itemArray[$count] to a string.

When you do $itemArray[$count][0] = 0; you are telling PHP to set the first character of $itemArray[$count] to 0 which is casts to a string.

In the old days of PHP, you could do this:

// create a string
$string = "Hello World!";

// reference the 2nd character in string
echo $string[1]; // "e"

PHP now discourages the array notation for strings in favor of curly braces like $string{1} instead, but the array notation still works.

I suspect the usage of curly braces was to disambiguate array access from string index access, but the old square brackets still work.

If you want a 2-d array, you should do this:

$itemArray[$count] = array(); // make $itemArray[$count] an array
$itemArray[$count][0] = 0; // set index 0 to (int)0
$itemArray[$count][1] = $matches[1][$i]; // set index 1 to the match

Upvotes: 3

Related Questions