Get value from PHP SimpleXMLElement object ([0] => value) [duplicate] - php

This question already has answers here:
Forcing a SimpleXML Object to a string, regardless of context
(11 answers)
Closed 2 years ago.
$value = $simpleXmlDoc->SomeNode->InnerNode;
actually assigns a simplexml object to $value instead of the actual value of InnerNode.
If I do:
$value = $simpleXmlDoc->SomeNode->InnerNode . "\n";
I get the value. Anyway of getting the actual value without the clumsy looking . "\n"?

Cast as whatever type you want (and makes sense...). By concatenating, you're implicitly casting to string, so
$value = (string) $xml->someNode->innerNode;

You don't have to specify innerNode.
$value = (string) $simpleXmlDoc->SomeNode;

What about using a typecast, like something like that :
$value = (string)$simpleXmlDoc->SomeNode->InnerNode;
See : type-juggling
Or you can probably use strval(), intval() and all that -- just probably slower, because of the function call.

Either cast it to a string, or use it in a string context:
$value = (string) $simpleXmlDoc->SomeNode->InnerNode;
// OR
echo $simpleXmlDoc->SomeNode->InnerNode;
See the SimpleXML reference functions guide

Related

selecting array for array_push using Ternary Operator [duplicate]

This question already has an answer here:
Assigning variables by reference and ternary operator?
(1 answer)
Closed 1 year ago.
I have two arrays and I want to append to one or another based on a certain condition. The problem is that the array_push function should be called inside cases of a switch case inside a foreach loop, so using if-else means 20 extra lines of code. I thought I could do this using the Ternary Operator, but for some reason it doesn't work.
$arr1 = ['1', '2'];
$arr2 = ['a', 'b'];
$condition = False;
array_push($condition ? $arr1 : $arr2, 'new');
which produces this error:
array_push(): Argument #1 ($array) cannot be passed by reference
I thought $arr1 and $arr2 are references, and therefore you should be able to pass them, but something is not as it should be. At least that's how it behaves in C.
Have a look at the function signature for array_push():
array_push(array &$array, mixed ...$values): int
Notice the & in the first argument. That indicates that a reference must be passed.
Only variables can be passed by reference. A ternary expression is, well, an expression.
If you want to do this, you will need to first establish the reference, then pass it. And there's no easy way to shortcut that.
if( $condition) $ref = &$arr1; else $ref = &$arr2;
array_push($ref, 'new');
$ref = null; // clear reference

Need Explaination about Plus/Minus/Multiply and Devide in PHP [duplicate]

This question already has answers here:
PHP is confused when adding and concatenating
(3 answers)
Closed 6 years ago.
Today i am working on a small PHP code to plus/minus and multiply, but i end up found something which i wasn't knew before.
I was Plus 2 value, 123456+123456=24690 and my code is this:
<?php
$value1=12345;
$value2=12345;
$output=$value1+$value2;
echo $output;
?>
Which return a correct value:
So than i have to print this value with string Like this:
Total Value: 24690
I use this code:
echo 'Total Value:'.$value1+$value2;
Its return: 12345 instead of
Total Value: 24690
I know that "." isn't a Arithmetic operators, so i need small explanation why is this doing that.
But when i do
echo 'Total Value:'.($value1+$value2);
Its work fine!
Little Confused!
It first concatenates the $value1 with the string and then tries to add it to a string and number can't be added to string and hence you get that output.
While using braces, it just concatenates the contents of the brace and performs the mathematical operation inside the brace.
It follows BODMAS
When you
echo 'Total Value:'.$value1+$value2;
code execution will be like this actually:
echo ('Total Value: ' . $value1) + $value2;
This behavior is called Type Juggling. From the manual it states:
a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.
Example:
$foo = "1"; // $foo is string (ASCII 49)
$foo *= 2; // $foo is now an integer (2)
More examples on the link.

PHP equivalent for Python's repr() [duplicate]

This question already has an answer here:
PHP Array to String equivalent
(1 answer)
Closed 10 years ago.
I'm creating a simple array wrapper class and want it's __toString() method to be formatted like a Python list, eg: ["foo", "bar", 6, 21.00002351]. Converting each element to a string is not enough, since string-objects are actually enquoted in the list-representation.
Is there a repr() equivalent in PHP, and if not, what would a PHP implementation look like?
Python's repr() returns an output where
eval(repr(object)) == object
Called by the repr() built-in function and by string conversions (reverse quotes) to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).
So the closest thing in PHP would be
var_export — Outputs or returns a parsable string representation of a variable
The keyword here is parseable. While functions print_r and var_dump will give a certain representation of the data passed to them, they are not easily parseable, nor do they look like PHP expression, which could be eval'd.
Example:
var_export(['foo', 'bar', 1,2,3]);
will give
array (
0 => 'foo',
1 => 'bar',
2 => 1,
3 => 2,
4 => 3,
)
and that is perfectly valid PHP code:
$data = ['foo', 'bar', 1, 2, 3];
$repr = var_export($data, true);
// have to use it with return though to eval it back into a var
$evald = eval("return $repr;");
var_dump($evald == $data); // true
Another option would be to use serialize to get a canonical and parseable representation of a data type, e.g.
$data = ['foo', 'bar', 1, 2, 3];
$repr = serialize($data);
// -> a:5:{i:0;s:3:"foo";i:1;s:3:"bar";i:2;i:1;i:3;i:2;i:4;i:3;}
var_dump( unserialize($repr) == $data ); // true
Unlike var_export, the resulting representation is not a PHP expression, but a compacted string indicating the type and it's properties/values (a serialization).
But you are likely just looking for json_encode as pointed out elsewhere.
Making this a Community Wiki because I've already answered this in the given dupe.
I don't know Python but PHP arrays can contain any data type and nesting levels. I don't know how that translates into your format.
There're many functions to print an array:
print_r()
var_dump()
var_export()
... but your format reminds me of JSON so you can simply do this:
<?php
$foo = array (
'foo',
'bar',
6,
21.00002351,
);
echo json_encode($foo); // ["foo","bar",6,21.00002351]
Of course, it's by no means automatic, i.e., this won't trigger any toString() method at all:
echo $foo; // "Array" + PHP Notice: Array to string conversion

Weird PHP String Integer Comparison and Conversion

I was working on some data parsing code while I came across the following.
$line = "100 something is amazingly cool";
$key = 100;
var_dump($line == $key);
Well most of us would expect the dump to produce a false, but to my surprise the dump was a true!
I do understand that in PHP there is type conversion like that:
$x = 5 + "10 is a cool number"; // as documented on PHP manual
var_dump($x); // int(15) as documented.
But why does a comparison like how I mentioned in the first example converts my string to integer instead of converting the integer to string.
I do understand that you can do a === strict-comparison to my example, but I just want to know:
Is there any part of the PHP documentation mentioning on this behaviour?
Can anyone give an explanation why is happening in PHP?
How can programmers prevent such problem?
If I recal correcly PHP 'casts' the two variables to lowest possible type.
They call it type juggling.
try: var_dump("something" == 0);
for example, that'll give you true . . had that bite me once before.
More info: http://php.net/manual/en/language.operators.comparison.php
I know this is already answered and accepted, but I wanted to add something that may help others who find this via search.
I had this same problem when I was comparing a post array vs. keys in a PHP array where in my post array, I had an extra string value.
$_POST["bar"] = array("other");
$foo = array(array("name"=>"foobar"));
foreach($foo as $key=>$data){
$foo[$key]["bar"]="0";
foreach($_POST["bar"] as $bar){
if($bar==$key){
$foo[$key]["bar"]="1";
}
}
}
From this you would think that at the end $foo[0]["bar"] would be equal to "0" but what was happening is that when $key = int 0 was loosely compared against $bar = string "other" the result was true to fix this, I strictly compared, but then needed to convert the $key = int 0 into a $key = string "0" for when the POST array was defined as array("other","0"); The following worked:
$_POST["bar"] = array("other");
$foo = array(array("name"=>"foobar"));
foreach($foo as $key=>$data){
$foo[$key]["bar"]="0";
foreach($_POST["bar"] as $bar){
if($bar==="$key"){
$foo[$key]["bar"]="1";
}
}
}
The result was $foo[0]["bar"]="1" if "0" was in the POST bar array and $foo[0]["bar"]="0" if "0" was not in the POST bar array.
Remember that when comparing variables that your variables may not being compared as you think due to PHP's loose variable typing.

Strange PHP array behaviour [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP String in Array Only Returns First Character
I've got following problem. When I run script below I got string(1) "F" as an output. How is that possible? No error, notice displayed.. nothing. Key whatever doesn't exist in $c. Can you explain that?
<?php
$c = 'FEEDBACK_REGISTER_ACTIVATION_COMPLETED_MSG';
var_dump ($c['whatever']);
?>
I'm having this issue on PHP 5.3.3. (LINUX)
PHP lets you index on strings:
$str = "Hello, world!";
echo $str[0]; // H
echo $str[3]; // l
PHP also converts strings to integers implicitly, but when it fails, uses zero:
$str = "1";
echo $str + 1; // 2
$str = "invalid";
echo $str + 1; // 1
So what it's trying to do is index on the string, but the index is not an integer, so it tries to convert the string to an integer, yielding zero, and then it's accessing the first character of the string, which happens to be F.
Through Magic type casting of PHP when an associative array can not find the index, index itself is converted to int 0 and hence it is like
if
$sample = 'Sample';
$sample['anystring'] = $sample[0];
so if o/p is 'S';

Categories