Getting information from an XML object in PHP - php

I am using some XML parser to get some information from API, blah blah... :)
In one place in my script, I need to convert string to int but I'm not sure how...
Here is my object:
object(parserXMLElement)#45 (4) {
["name:private"]=>
string(7) "balance"
["data:private"]=>
object(SimpleXMLElement)#46 (1) {
[0]=>
string(12) "11426.46"
}
["children:private"]=>
NULL
["rows:private"]=>
NULL
}
I need to have this string "11426.46" stored in some var as integer.
When I echo $parsed->result->balance I get that string, but if I want to cast it as int, the result is: 1.
Please help!
Thanks a lot!

you have an object, intval of an object will always be 1(if it doesnt have a __toString() magic method defined).
you can intval SimpleXMLElement and it will return 11426, but to do that, the data member of the parserXMLElement class has to be public. you might need to define a getData() method for the parserXMLElement class or make the data member public.

You need to use intval. For example:
echo intval($parsed->result->balance);
will output the value as an integer - assuming that balance is a string.

Related

Is Empty and NULL the same in a comparision operation in PHP?

I have a class that has a method that expects a response from an API service in array format. This method then converts the response array into an object by casting (object)$response_array. After this the method attempts to parse the contents of the object. There is a possibility that the returned array could be empty. Before parsing the contents of the object in my class method, I perform a check for null or empty object in an if...else block. I would like to use an equivalence comparison operator like if($response_object === null){} and not if(empty($response_object)){}.
Below is how my class looks like
<?php
class ApiCall {
//this method receives array response, converts to object and then parses object
public function parseResponse(array $response_array)
{
$response_object = (object)$response_array;
//check if this object is null
if($response_object === null) //array with empty content returned
{
#...do something
}
else //returned array has content
{
#...do something
}
}
}
?>
So my question is - is this the right way to check for empty object, without using the function empty() and is it consistent? If not then how can I modify this code to get consistent results. This would help me know if null and empty mean the same thing in PHP objects. I would appreciate any answer where I can still use an equivalent comparison like this ===
It is not the right way to check for an empty object. If you call your function parseResponse with an empty array, the if condition will still be false.
So, if you would put echo in the if-else code like this:
class ApiCall {
//this method receives array response, converts to object and then parses object
public function parseResponse(array $response_array)
{
$response_object = (object)$response_array;
//check if this object is null
if($response_object === null) { // not doing what you expect
echo "null";
}
else {
echo "not null";
}
}
}
Then this call:
ApiCall::parseResponse(array()); // call with empty array
... will output
not null
The same happens if you test for empty($response_object). This used to be different in a distant past, but as from PHP 5.0 (mid-2004), objects with no properties are no longer considered empty.
You should just test on the array you already have, which is falsy when empty. So you can just write:
if(!$response_array) {
echo "null";
}
else {
echo "not null";
}
Or, if you really want an (in)equality, then do $response_array == false, making sure to use == and not ===. But personally, I find such comparisons with boolean literals nothing more than a waste of space.
All of the following would be working alternatives for the if condition:
Based on $response_array:
!$response_array
!count($response_array)
count($response_array) === 0
empty($response_array)
Based on $response_object:
!get_object_vars($response_object)
!(array)($response_object)
Note that get_object_vars could give a different result than the array cast method if $response_object were not a standard object, and would have inherited properties.
Look at this example
$ php -a
php > $o = (object)null;
php > var_dump($o);
class stdClass#2 (0) {
}
php > var_dump(!$o);
bool(false)
So, it is not good idea to compare object with null in your case. More about this: How to check that an object is empty in PHP?

unset property in function also affecting passed variable

I have the following code
<?php
$foo[0] = new stdclass();
$foo[0]->foo = 'bar';
$foo[0]->foo2 = 'bar';
destroy_foo($foo);
var_dump ($foo);
function destroy_foo($foo)
{
unset($foo[0]->foo);
}
?>
The output is
array(1) { [0]=> object(stdClass)#1 (1) { ["foo2"]=> string(3) "bar" } }
I would expect $foo[0]->foo to still exist outside the function, but it doesn't. If I remove the properties and just use an array instead, it works. If I change the variable name inside the function, same problem. How can I use properties but make it work as expected?
What you see as an error is a PHP behaviour that's "working as expected": see the objects and references official guide.
It's not clear what you want to achieve with your code, but you should try to pass a clone of your object to the function.
In PHP Objects will only free their resources and trigger their __destruct method when all references are unsetted. So, to achieve your desire result, you have to
assign null insteadof unsetting it.
$foo[0]->foo = null;

Automatic conversion from int to string in PHP

In PHP, I have a variable of the type Integer.
When I pass it to a function, it's converted to a string.
I tested it with var_dump. It's an integer when I call the function.
Directly after the function call, it's a string.
Code:
public function setId($id)
{
var_dump($id);
// call of method "checkIfInteger" --> is_int($arg)
}
EDIT: Ok guys, I got it. In my setId method, I had another check method that trimmed the parameter (&$id) - when I enter ' 10 ' for example, I worked with a (trimmed) string afterwards.
Another question:
I use intval, but intval('OK') returns an integer.
'25' should return true, 25 too, 2.5 should return false, and 'ok' too.
Is there a function available?
A variable is not converted to a string. Quick check:
<?php
function setId($id)
{
var_dump($id);
// call of method "checkIfInteger" --> is_int($arg)
}
$a = 1;
setId($a);
Result is: int(1)
Where is your $id comming from? How do you know that it's an int before the method call?
//Where ever you wanted an integer, why not try this.?
int $id = intval($id, 0);
Hope that helps
That depends on how you send the parameter to your function...
Seems like you sent the param like this...
setId("1");// which will be a string ofcourse...
Try sending as setId(1); you will get integer in your var_dump output.
EDIT :
<?php
$id=1;
if(gettype($id)=="integer")
{
setId($id);
}
else
{
echo "Function will not be called because ID is not an integer!";
}
function setId($id)
{
var_dump($id);
}

how arguments are passed to codeigniter method

I have a method in a codeigniter controller which is sometimes called through the url and sometimes called internally from another method of the controller. When I call it internally I pass an array of arguments. Simplified version of method:
(within a controller)
function get_details($args='') {
if (isset($args['first_name']))
{
$first_name = $args['first_name'];
}
else
{
$first_name = $this->uri->segment(3);
}
... do some other stuff ...
}
The method is either called as:
<domain>/<controller>/get_details/abcd/efgh
or from another function of the controller as:
$this->get_details(array('first_name'=>'abcd', 'last_name'=>'efgh'));
I was expecting that when the method was called through the url, isset($args['first_name']) would be false, however it seems that called in this way the argument is there. I tried printing a couple of things and this is what I got:
print_r($args) ----> abcd
echo($args['first_name']) ----> a
echo($args['whatever_index_I_use']) ----> a
It seems like the third parameter of the url is being passed into the method (by codeigniter?), but can't work out why the array indexes seem to be set, all I can think is that php is converting the string to an int, so $args['whatever_index_I_use'], becomes $args[0]??
Not sure if this is a codeigniter thing or me missing a subtlety of php.
Much appreciate anyone who can explain what's going on.
Thanks.
I don't know if this is a bug or a expected behavior, but in the Strings docs there's a comment that show exactly what are you experiencing. If you use a text and index of the string it will return the first char. To avoid it, check first if the argument is an array or a string:
if(is_array($args)) {
echo($args['first_name']);
}
To complete #SérgioMichels answer, the reason for that is because PHP is expecting an integer as the given index. When you give it a string, PHP will cast the string into an integer, and assuming that the string does not start with a number, type casting will return 0 otherwise, it will return the leading number.
$str = 'abcdefghi';
var_dump($str['no_number']); // Outputs: string(1) "a"
var_dump($str['3something']); // Outputs: string(1) "d"
To specifically answer your question - this will solve your bug:
function get_details($args='')
{
if (is_array($args))
{
$first_name = $args['first_name'];
}
else
{
$first_name = $this->uri->segment(3);
}
... do some other stuff ...
}
But you have some issues with your code. Firstly you state that you call the method as
<domain>/<controller>/get_details/abcd/efgh
but you dont accept the "efgh" variable in your controller. To do this, you need to change the function to
function get_details($first, $last)
in which case you can now just call the function as
$this->get_details('abcd', 'efgh');
and now you dont even need to test for arrays etc, which is a better solution IMO.
If you decide to stick with arrays, change:
$first_name = $this->uri->segment(3);
to
$first_name = $args;
because by definition - $args IS The 3rd URI segment.

How to get PHP Function value?

When using a funciton for example, "get_photo_id" and I use the number 6 inside.
EXAMPLE:
<?php get_photo_id("6"); ?>
i want the function get_photo_id to get the value inside (which is 6 in this case). To be able to find the number inside and assign a variable to it.
Something like this:
function get_photo_id() {
<!--something to find the value used and assign it as $valueused -->
get_cat_id('$valueused')
echo 'cat_id'
}
I hope you get what i mean... im kind of new in php!
Function arguments are passed as follows:
function foo($argument1, $arg2)
{
var_dump($argument1, $arg2, func_get_args());
}
foo("test", 12);
results in
string(4) "test"
int(12)
array(2) { [0]=> string(4) "test" [1]=> int(12) }
Do you mean function parameters?
function foo($arg)
{
echo $arg;
}
When you call foo("6") it will echo 6. However, if you want to work with numbers, its better to call foo(6) with a number, instead of a string containing a number.
I am not clear about your question, but this might be the answer from what i understand
function get_photo_id($value) {
<!--something to find the value used and assign it as $valueused -->
get_cat_id($value);
echo 'cat_id'
}

Categories