This question already exists:
Closed 11 years ago.
Possible Duplicate:
Access array element from function call in php
instead of doing this:
$s=explode('.','hello.world.!');
echo $s[0]; //hello
I want to do something like this:
echo explode('.','hello.world.!')[0];
But doesn't work in PHP, how to do it? Is it possible? Thank you.
As the oneliners say, you'll have to wait for array dereferencing to be supported. A common workaround nowadays is to define a helper function for that d($array,0).
In your case you probably shouldn't be using the stupid explode in the first place. There are more appropriate string functions in PHP. If you just want the first part:
echo strtok("hello.world.!", ".");
Currently not but you could write a function for this purpose:
function arrayGetValue($array, $key = 0) {
return $array[$key];
}
echo arrayGetValue(explode('.','hello.world.!'), 0);
It's not pretty; but you can make use of the PHP Array functions to perform this action:
$input = "one,two,three";
// Extract the first element.
var_dump(current(explode(",", $input)));
// Extract an arbitrary element (index is the second argument {2}).
var_dump(current(array_slice(explode(",", $input), 2, 1)));
The use of array_slice() is pretty foul as it will allocate a second array which is wasteful.
Not at the moment, but it WILL be possible in later versions of PHP.
This will be possible in PHP 5.4, but for now you'll have to use some alternative syntax.
For example:
list($first) = explode('.','hello.world.!');
echo $first;
While it is not possible, you technically can do this to fetch the 0 element:
echo array_shift(explode('.','hello.world.!'));
This will throw a notice if error reporting E_STRICT is on.:
Strict standards: Only variables should be passed by reference
nope, not possible. PHP doesn't work like javascript.
No, this is not possible. I had similar question before, but it's not
Related
I am having to do:
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
I want to avoid that redundant mention of the variable name. I tried:
htmlspecialchars_decode(&$sourceElement['description']);
and
call_user_func('htmlspecialchars_decode', &$sourceElement['description']);
That did not work. Is this possible in PHP? Call a function on a variable?
You could create your own wrapper function that takes the variable by reference:
function html_dec(&$str) {$str = htmlspecialchars_decode($str);}
Then call:
html_dec($sourceElement['description']);
The correct solution would be to include that "redundant" variable mention. It's far more readable, and far less confusing that way.
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
Your way of thinking is good though, you're thinking how to shorten your code, like a true lazy programmer =)
It depends on function. htmlspecialchars_decode() returns the result, it doesn't modify the original variable. And you can do nothing about it.
Most functions in PHP are immutable in mature, i.e. they don't modify the arguments you pass into them. This has a few advantages, one of them being able to use their return value in expressions without side effects.
Here's a generic wrapper you could use to mimic mutable behaviour for any function that takes a single argument:
function applyFn(&$s, $fn)
{
return $s = $fn($s);
}
applyFn($sourceElement['description'], 'htmlspecialchars_decode');
applyFn($sourceElement['description'], 'trim'); // trim string
Mileage may vary :)
I'm looking for the kind to access at the value of an array directly from the object's method.
For example :
With this syntax, no problem :
$myArray = $myObject->getArray();
print_r($myArray[0])
But to reduce the number of line in source code, how to get the element directly with the method ?
I do that, but it's not correct :
$myArray = $myObject->getArray()[0];
The following is only available for PHP 5.4 and supposedly higher.
$myArray = $myObject->getArray()[0];
Unfortunately there is no quicker way below PHP 5.4.
See #deceze's answer for a good alternative.
For PHP 5.3-:
$myArray = current($myObject->getArray());
or
list($myArray) = $myObject->getArray();
If you are on php 5.4 (which support array dereferencing) you can do the second option:
$myArray = $myObject->getArray()[0];
If you are on PHP < 5.4 you can "fix" it in the class (of which the object is a instance):
class Foo
{
public function getArray()
{
return $this->theArray;
}
public function getFirstItem()
{
return $this->theArray[0];
}
}
$myObject = new Foo();
print_r($myObject->getFirstItem());
But to reduce the number of line in source code, how to get the element directly with the method ?
Although it is possible to achieve this in PHP 5.4 with the syntax you've demonstrated, I have to ask, why would you want that? There are ways of doing it in 5.3 in a one-liner, but I don't see the need to do this. The number of lines is surely less interesting than the readability of the code?
IT IS IMPOSSIBRRUUU.
Serious answer:
sadly it is not possible. You can write a very ugly wrapper like this:
function getValue($arr, $index)
{
return $arr[$index];
}
$myArray = getValue($myObject->getArray(), 0);
But that makes less readable code.
read other answers about php 5.4 Finally!
Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().
Out of curiosity, are the two options below functionally equivalent?
$array_variable = function_that_creates_an_array();
foreach($array_variable as $a){
do_something()
}
vs.
foreach(function_that_creates_an_array() as $a){
do_something()
}
Just want to make sure I'm not calling the function on every iteration or anything dumb like that.
Thanks!
Yes, they are basically equivalent.
The only difference is the first one will add a variable to the current scope (i.e. if your in the global scope).
The two snippet will read the array the same way, without re-evaluation the function.
Nevertheless, in the second snippet, you will not be able to access to the complete array during the loop since you don't have any reference (variable) on it.
http://www.php.net/manual/en/control-structures.foreach.php
Simply, yes they are functionally the same.
In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)
The technical answer is that the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages. I've always viewed it as a deficiency in the language, because it is possible to have a grammar that resolves subscripts against any expression unambiguously. It could be the case, however, that they're using an inflexible parser generator or they simply don't want to break some sort of backwards compatibility.
Here are a couple more examples of invalid subscripts on valid expressions:
$x = array(1,2,3);
print ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.
function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, on a call expression, not a variable exp.
This is called array dereferencing. It has been added in php 5.4.
http://www.php.net/releases/NEWS_5_4_0_alpha1.txt
update[2012-11-25]: as of PHP 5.5, dereferencing has been added to contants/strings as well as arrays
I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
Or, you could write a small function:
function indexonce(&$ar, $index) {
return $ar[$index];
}
and call this with:
$something = indexonce(array('a', 'b', 'c'), 2);
The array should be destroyed automatically now.
This might not be directly related.. But I came to this post finding solution to this specific problem.
I got a result from a function in the following form.
Array
(
[School] => Array
(
[parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a
)
)
what i wanted was the parent_id value "9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a".
I used the function like this and got it.
array_pop( array_pop( the_function_which_returned_the_above_array() ) )
So, It was done in one line :)
Hope It would be helpful to somebody.
function doSomething()
{
return $somearray;
}
echo doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();
actually, there is an elegant solution:) The following will assign the 3rd element of the array returned by myfunc to $myvar:
$myvar = array_shift(array_splice(myfunc(),2));
Or something like this, if you need the array value in a variable
$variable = array('a','b','c');
$variable = $variable[$key];
There are several oneliners you could come up with, using php array_* functions. But I assure you that doing so it is total redundant comparing what you want to achieve.
Example you can use something like following, but it is not an elegant solution and I'm not sure about the performance of this;
array_pop ( array_filter( array_returning_func(), function($key){ return $key=="array_index_you_want"? TRUE:FALSE; },ARRAY_FILTER_USE_KEY ) );
if you are using a php framework and you are stuck with an older version of php, most frameworks has helping libraries.
example: Codeigniter array helpers
though the fact that dereferencing has been added in PHP >=5.4 you could have done it in one line using ternary operator:
echo $var=($var=array(0,1,2,3))?$var[3]:false;
this way you don't keep the array only the variable. and you don't need extra functions to do it...If this line is used in a function it will automatically be destroyed at the end but you can also destroyed it yourself as said with unset later in the code if it is not used in a function.