PHP - get first value from array with single line using native functions - php

I have a function asdf() that returns an array ["key" => "value"]. I would like to print out value with one line, but reset() function suggested in similar questions does not work for me because reset only takes variable as a argument and doesent accept function. So if i try reset(asdf()) i get an exception: "Only variables should be passed by reference".
So my question is how can i print "value" from asdf() in a single line only using php native functions.

Actually reset function used to move the array's internal pointer to the first element, I think you must use current function that is return the current element in an array
Try like this
print current(asdf());

Try this:
current(array_values(asdf()));
It uses current to avoid the pass by reference error and array_values to ensure the array passed to current has the first element as it's current element.
Though unless you have a very good reason assigning the array to a variable and then using reset would be better.

Related

Unable to get dynamic PHP's Object value using PHP variable

PHP is unable to get the value for dynamic object prepared as:
$abc->{$dynamic_object_pattern}
Where the value of the variable $dynamic_object_pattern is, json->{'data_1'}->{'value'}
For me, PHP 7.1 is understanding the statically defined pattern like below, and fetching the value as it should:
$abc->json->{'data_1'}->{'value'}
But not when I put the whole portion into a variable and then try to get its value. I Tried,
$abc->{$dynamic_object_pattern} and $abc->$dynamic_object_pattern
both ways, but no solution yet.
The error comes is Notice: Undefined property: stdClass::$json->{'data_1'}->{'value'}
I'm attempting an answer without seeing your JSON data
Here you say :
But not when I put the whole portion into a variable and then try to
get its value
From that line alone it sounds like you are trying to get value from a string rather than array. If you put the whole portion into a variable, PHP will interpret it as string. Make sure you add array() before newly created variable.
Natural array :
$array = array();
Now a string
$variable = $array;
Convert string to array
$new_array = array($variable);
Also, have you tried decoding?
// decode
$response = json_decode($new_array, true);
//print out
var_export(array_unique(array($response)));

My array isn't recognized as array when it contains only one value

In my code, I fill an array using this line in a loop :
$_SESSION['my_array'][] = $some_value;
After each execution of this line, I do some check (doesn't matter here for which purpose) using the function in_array(). However, at the first iteration it says :
« in_array() expects parameter 2 to be array ».
How to fix this problem?
You can initialize the array (before you fill it with values) like this:
$_SESSION['my_array']=array();
This way you can be sure that it is array, even when it would be empty.
You are assigning or accesing it wrongly
Use this
$_SESSION['my_array'] = $some_value;
When you are doing the in_array check, you can cast the second item to an array, so if it's empty then it will pass an empty array. This way you don't ever set anything to the session when you don't need to (which could trip you up later on)
e.g.,
if (in_array('foo', (array)$_SESSION['my_array'])) {
// do something
}

Return Array Element without Creating Variable

I feel stupid for asking this cause it seems so basic but it's really bugging me.
I have a method that returns an array with a single element. I just want it to return the element not wrapped in an array. I tried this.
return $f->getValue()[0];
and it gives an error but if I save it to a variable, it works fine.
$v = $f->getValue();
return $v[0];
I can't figure it out....
It's available only since PHP 5.4: http://codepad.viper-7.com/VHOW0o
What you are trying to do, is called array dereferencing, and is only possible in PHP as of version 5.4 (if you scroll up a few lines in the documentation article I linked to, you'll see it mentioned).
Use reset().
<?php return reset( $f->getValue() ); ?>
Edit: reset() is probably superior to current() as it also makes sure that the internal pointer is reset, despite it not making much difference if the array only contains one element.
As far as I know since you are returning an array you only can get an array. You can instead save the array to a variable in the class (accessible by $f->myArray) and then return just the string portion. Or the other option is to do what your second example is and return the array and retrieve the string from it.
have you tried this
<?php
return array_shift(array_values($array));
?>
Get the first element of an array

Better way to get first element of returned array

I found myself using this:
$var=(string)array_shift(array_values($item->xpath($s)));
where $s is an xpath search string and the return is an array of objects that contain strings.
It works, but I'm not sure it's the best way to get the data I want.
I could use a tempvar, but I wanted to avoid that.
Any suggestions?
Careful with array_shift, as it will remove the element from the array stack, if you simply want the first value, you can use current:
$var = (string) current($item->xpath($s));
I believe this gives the same result.
$var=array_shift($item->xpath($s));
$var = $reset($item->xpath($s));
Note that this rewinds the array's internal pointer and returns the first element. The method current returns the element at the position the pointer happens to be in - it is not guaranteed to always be the first element.

How to call a function with a variable number of parameters which correspond to an array values?

OK, I know it sounds weird but I need to make a function that will receive two parameters the first one is a string and the second an array (containing strings).
This function will then call sprintf. My first parameter will be $format and my array will correspond to the various $args.
How can I achieve this (if possible)?
Thanks!
Well you want the vsprintf() function.
Like Orbling answered, for this particular case you need vsprintf.
But, in a generic case, to call a function with variable number of parameters, you can use func_get_args() inside the function which you desire to accept multiple (any number of variable arguments). This function (when called inside your function) returns an array containing all the parameters passed while calling your function.

Categories