user1001336
user1001336

Reputation: 19

Access first element of an array without index

i have an xml file:

    <?xml version="1.0" encoding="utf-8" ?>
    <transaction dsxml_version="1.08">
    <action>action1</action>
    <action>action2</action>
    </transaction>

If i use simplexml i can access the first "action" with die following code

    $xml = simplexml_load_string($xml_content);
    echo $xml->action; // Write "action1"
    echo $xml->action[0]; // Write "action1"
    echo $xml->action[1]; // Write "action2"

Now i create an array and a try to access it on the same way. But it doesent work.

We have a huge php skipt which use simple xml which contains a logical error. If i can emulate simple xml i can fix this error on one position

Upvotes: 1

Views: 620

Answers (5)

hakre
hakre

Reputation: 197682

You can create a fake or mock object that simulates the behaviour you are looking for:

$action = new SimpleXMLArrayMock($action_array);

$xml->action = $action;

echo "\nFake:\n";
echo $xml->action, "\n";    // Write "action1"
echo $xml->action[0], "\n"; // Write "action1"
echo $xml->action[1], "\n"; // Write "action2"


/**
 * Mock SimpleXML array-like behavior
 */
class SimpleXMLArrayMock extends ArrayObject
{
    private $first;
    public function __construct(array $array)
    {
        $this->first = (string) $array[0];
        parent::__construct($array);
    }
    public function __toString()
    {
        return $this->first;
    }

}

Demo

Upvotes: 1

poplitea
poplitea

Reputation: 3737

This would work:

foreach($myarray as $key => $val)
{
    print $val;
    //if you don't need the rest of the elements:
    break;
}

Added:

You can even make it a function:

function get_first_element($myarray)
{
    foreach($myarray as $key => $val)
    {
        return $val;
    }
}

Upvotes: 0

Ben Swinburne
Ben Swinburne

Reputation: 26467

echo array_shift(array_slice($xml->action, 0, 1));

or if you're not worried about damaging the original array, $xml->action you can use the following

echo array_shift($xml->action);

Using array_shift will guarantee you get the first element if it's numbered or associative.

Upvotes: 1

JellyBelly
JellyBelly

Reputation: 2431

try this:

current($xml->action);

Upvotes: 1

ka_lin
ka_lin

Reputation: 9432

use xpath so you can find the element

Upvotes: 0

Related Questions