Access first element of an array without index - php

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

try this:
current($xml->action);

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.

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

use xpath so you can find the element

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;
}
}

Related

Php class property get and set

I have the following codes.
<?php
class Reg {
private $pros = array();
public function __set($key,$val) {
$this->pros($key)= $val;
}
public function __get($key) {
return $this->pros($key);
}
}
$reg= new Reg;
$reg->tst="tst";
echo $reg->tst;
?>
But when executing this script I got the error following.
Fatal error : can't use method return value in write context in line 5
I believe that to add an element to array is possible like the above.
$array = array();
$array('key')='value';
Please make clear that I was wrong.
Thanks
The is because of you are trying to set a functions return value. $this->pros($key) means calling pros($key) function. Not setting a value to $pros array.
The syntax is wrong. Setting values to array be -
$array['index'] = 'value';
Change
$this->pros($key)= $val; -> $this->pros[$key]= $val;
and
return $this->pros[$key];
Working code
$this->pros[$key] = $value;
OR
$keys = array($key);
$this->pros = array_fill_keys($keys,$value);
The array_fill_keys() function fills an array with values, specifying keys.
Syntax:
array_fill_keys(keys,value);

function stored inside array

i want to call function store inside array but before i do it i want to check if it is function,string or any other type.
please take a look at my code
$a=new stdClass();
$array = array(function() {
return "Bhavik Patel";
}, "1213",$a);
foreach ($array as $key => $value) {
if (is_object($value)) {
echo $value() . "<br/>";
} else {
echo $value . "<br/>";
}
}
by doing this i can check if value is object then i call it but if i pass object it gives (pf course this will give error)
my intention is to find if value is function then call it.
To check specifically for anonymous functions you can test the value against \Closure like so:
if ($value instanceof \Closure) {
echo $value(), "\n";
} else {
echo $value;
}
The problem with is_callable() is that if your value is "explode", it will return true which is obviously not what you want.
is_callable() will help you, but notice that if you pass an array like this
array('object or class','method')
is_callable() return true, so you'd better to check it isn't an array
if (is_callable($value) && !is_array($value)) {.....}
see is_callable
Try [is_callable][1] in PHP. I have tested it, it works for me.

How to access contents of a keyless array to object conversion?

I'm experimenting with OOP and PHP.
I don't know why I would ever need to do something like this but I'm wondering how it would be done and cant find it online.
class Example{
public $a = 'aye';
public $b = 'bee';
public $c = 'see';
public function how(){
return (object)array(
$this->a,
$this->b,
$this->c
);
}
}
$example = new Example;
$how = $example->how();
echo $how->1; //I thought would print bee
I'm aware that giving the array keys would let me do
echo $how->beekey //which would give me beekey's value
This is basically not possible, as explained in this bug report; numeric object properties are kind of a gray area in PHP.
However, you can cast the object back to an array and reference the value:
$arr = (array)$how;
echo $arr[1];
Or, use as a one-liner:
echo current(array_slice((array)$how, 1, 1));
The best advice I could give you is to not turn it into an object in the first place:
public function how()
{
return array(
$this->a,
$this->b,
$this->c
);
}
And then just reference it as $how[1].
Btw, $how->{1} used to work in PHP 4 :)
What about using a loop?
foreach($how as $value)
{
echo $value .'<br>'; //this print your values: aye<br>bee<br>see
}

How do I return a value from a PHP multi-dimensional array using a variable key?

I am having trouble returning a value from a multidimensional array using a key ONLY when I externalize to create a function.
To be specific, the following code will work when inline in a page:
<?php
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') echo $key['uiString'];
}
?>
However, if I externalize the code as a function, like so:
function getUIString($myKey) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
}
}
return $myString;
}
And then call it like this:
<?php getUIString('global001'); ?>
It always returns -1, and will do so even if I use an explicit key in the function rather than a variable. I can't understand why this works inline, but fails as a function.
I'm a relative PHP noob, so please forgive me if this includes a glaring error on my part, but I've searched all over for discussion of this behavior and found none.
All help appreciated.
i think you need to take a look at PHP's Variable Scope. To problem is that PHP isn't typical of other languages where a variable defined outside of a function is visible within. You need to use something like the $GLOBALS variable or declare the variable global to access it.
To better illustrate, picture the following:
$foo = "bar";
function a(){
// $foo is not visible
echo $foo;
}
function b(){
global $foo; // make $foo visible
echo $foo;
}
function c(){
// acccess foo within the global space
echo $GLOBALS['foo'];
}
The same is basically holding true for your $uiStringArray variable in this scenario.
This is a problem with variable scope, see Brad Christie's answer for more details on variable scope.
As for your example, you need to either pass the array to the function or create it inside the function. Try:
function getUIString($myKey, $uiStringArray = array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}
And call the function using
<?php getUIString('global001', $uiStringArray); ?>
You are having this problem because you are overriding you $mystring variable even if it matches. Send your array as your parameter. It is unknown to your function.You just use break if variable matches
function getUIString($myKey, $uiStringArray=array()) {
// step through the string array and find the key that matches the uid,
// then return uiString
$myString = "-1";
foreach ($uiStringArray as $key) {
$keyVal = $key['uid'];
if($keyVal == 'global001') {
$myString = $key['uiString'];
break;
}
}
return $myString;
}

PHP global declaration

I'm using PHP's global declaration to make an array available to a number of functions in a script. The variable is declared at the top of the script and is referenced with global in each of the functions which uses it, as follows:
<?php
$myarray = array(1, 2, 3);
function print_my_array() {
global $myarray;
print '<ul>';
foreach($myarray as $entry) {
print '<li>'.$entry.'</li>';
}
print '</ul>';
return 0;
}
print_my_array();
?>
Sometimes, but not always, the array is not set when the function is called, generating an error when the foreach is called. In the actual code, the array used is given a very unique name and so should not be causing any collisions with anything else. Am I mis-using the global declaration?
No, the snippet is correct. The problem you're having is the problem of using global variables – they can be accessed and changed from anywhere (perhaps accidental), thereby creating hard-to-find bugs.
By using globals you can hit quite a few gotchas, they'll also make you code less reusable.
Here's an example of your function which can be re-used many times across the site.
(untested)
<?php
function arrayTags($items, $open = '<li>', $close = '</li>')
{
if (is_array($items) && count($items) != 0)
{
$output = null;
foreach ($items as $item) {
$output .= $open . $item . $close;
}
return $output;
}
else
{
return '';
}
}
// Default, <li>
echo '<ul>' . arrayTags($myarray) . '</ul>';
// or, spans:
echo '<div id="container">' . arrayTags($myarray, '<span>', '</span>') . '</div>';
The least you could do is check if the array is null at the top of the function, before you run the foreach. that would at least prevent the error:
function print_my_array() {
global $myarray;
if(!empty($myarray)) {
print '<ul>';
foreach($myarray as $entry) {
print '<li>'.$entry.'</li>';
}
print '</ul>';
}
}
Also, I wouldn't just return 0 for the hell of it. You may want to incorporate whether or not the array was empty into what you return from this function.
$myarray = array(1, 2, 3);
In short you have to only declare it like so:
$myarray = array();
and if you want to populate it with values do that in the class constructor:
public function __construct(){
$myarray = array(1,2,3);
}
I'm no guru, but in my experience it seems that php doesn't like to execute function calls outside of a function within a class.
THIS DOES NOT WORK:
class MyClass {
public $mystring = myfunction();
public function myFunction(){
return true; //and your function code
}
}
so when you use array() it doesn't actually trigger any function call, it just creats an empty variable of type array. when you use array(1,2,3), it has to effectively run the 'create array' which is like a function.
I know annoying, I'd like it to be different, but I don't know a way of doing what you want in php. Let me know if there is a nice way I'd love to hear it!

Categories