Categories
PHP Programming

PHP: How to array_merge Without Losing Numeric Keys

PHP function array_merge is nice in that you can easily merge one (or more) arrays into a single array with a single call of the function. The keys are retained, but only if they’re not numeric keys(!).

E.g.

 "hi");
$array2 = array(3 => "data");
$result = array_merge($array1, $array2);
?>

Result:
Array
(
    [0] => hi
    [1] => data
)

Perhaps this is the behavior you want. But what if you want to retain the original numeric keys?

Advertisement
Categories
PHP Programming

Convert XML to array and vice versa in PHP

As a developer, it is common to search the web for an existing (open source) code snippet to re-use for an application, but it is rare for the developer to just copy code online and use it straight in their application without modifying it first.

I am one of many developers who like to save time if possible by using open source code if coding from scratch takes longer than a couple of minutes, but there are times when one cannot be found. I ran into such situation when I wanted a function that converts an XML string into an array. Unfortunately, most are overly complicated for what I wanted, so I decided to create my own and share with the world. The following function converts XML strings into a PHP array while retaining the level depths of the XML but all attributes are ignored.