$expode_top[] & $expode_bottom[] usage - php

I'm rewriting a PHP plugin, and there are functions called $expode_top[] & $expode_bottom[]. I understand what the normal explode function does, but what are these?
It seems to be impossible to find an answer on Google because it replaces the underscore with a space.

Those are array variables, not functions, they just happen to start with a keyword you are familiar with. Anything beginning with a $ is a variable in PHP.
Using [] will put the assigned variable into the "next" position of the array. For example:
$expode_top = array();
$expode_top[] = "testing";
if ( $expode_top[0] == "testing" ){
echo "it does equal testing";
}
As #gwillie rightly commented, it could also be a variable function - the name of the variable is replaced and then that function is executed. Second example:
$expode_top = "echo";
$expode_top("testing");
Is functionally the same as:
echo("testing");

Those are array variable names, not functions, as indicated by the $ and []. Also, neither exists as a function.

Related

PHP Variable Function Array Value

I need to use variable function names for a project I'm working on but have run into a bit of strange issue. The function name ends up as a string element in an array.
This works:
$func = $request[2];
$pages->$func();
This doesn't:
$pages->$request[2]();
And I can't figure out why. It throws an array to string conversion error, as if it's ignoring that I have supplied a key to a specific element. Is this just how it works or am I doing something wrong?
As for php 5, you can use curly-braced syntax:
$pages->{$request[2]}();
Simple enough example to reproduce:
<?php
$request = [
2 => 'test'
];
class Pages
{
function test()
{
return 1;
}
}
$pages = new Pages();
echo $pages->{$request[2]}();
Alternatively (as you noted in the question):
$methodName = $request[2];
$pages->$methodName();
Quote from php.net for php 7 case:
Indirect access to variables, properties, and methods will now be
evaluated strictly in left-to-right order, as opposed to the previous
mix of special cases.
Also there is a table for php 5 and php 7 differences for this matter just below quote in the docs I've supplied here.
Which things you should consider:
Check value of the $request[2] (is it really a string?).
Check your version of php (is it php 5+ or php 7+?).
Check manual on variable functions for your release.

Is it possible to print php variable withing a variable?

I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.

PHP preg_match: How is this passing of a variable to preg_match working?

This finds what it is supposed to:
if(!preg_match($match="/^http\/[0-9]+\\.[0-9]+[ \t]+[ \t]*(.*)\$/i",$line,$matches))
But this does not:
if(!preg_match("/^http\/[0-9]+\\.[0-9]+[ \t]+[ \t]*(.*)\$/i",$line,$matches))
The function reference for preg_match says that the first argument passed should be:
The pattern to search for, as a
string.
But the working example I give above assigns the pattern to a variable: $match=...
What is going on here? I have never seen a variable used with preg_match like that. I thought it should be:
preg_match(string $regexpattern, string $thingtosearch, array $matches)
Can anyone explain what's happening here?
The first example saves the pattern to a local variable.
if(!preg_match($match="/^http\/[0-9]+\\.[0-9]+[ \t]+[ \t]*(.*)\$/i",$line,$matches))
It is equivalent to writing it like that:
$match="/^http\/[0-9]+\\.[0-9]+[ \t]+[ \t]*(.*)\$/i";
if(!preg_match($match,$line,$matches))
The preg_match function doesn't "see" that the parameter was assigned to a variable, it only ever receives the value - because there are no named function parameters in PHP. It's hence unimportant how you name the local variables, and the $param definition in the manual has zero influence over functionality.
A probable explanation for this code structure is that the regex pattern $match might be reused later on. Sometimes this notation is just used for readability. (It's garbaging up the local variable scope, yet adds some minor clarity.)
An assignment expression returns the value that was assigned. So in your case the assignment expression $match="…" returns the assigned value "…" that results in the same parameter for the function as without that assignment.
Doing it that way is useful in some cases like in a condition of while:
while ($row = mysql_fetch_array($result))
Here $row = mysql_fetch_array($result) returns the same value that was returned by mysql_fetch_array($result) but it’s also assigned to $row.

PHP variable variables in {} symbols

I get the basics of variable variables, but I saw a syntax just know, which bogles my mind a bit.
$this->{$toShow}();
I don't really see what those {} symbols are doing there. Do they have any special meaning?
PHP's variable parser isn't greedy. The {} are used to indicate what should be considered part of a variable reference and what isn't. Consider this:
$arr = array();
$arr[3] = array();
$arr[3][4] = 'Hi there';
echo "$arr[3][4]";
Notice the double quotes. You'd expect this to output Hi there, but you actually end up seeing Array[4]. This is due to the non-greediness of the parser. It will check for only ONE level of array indexing while interpolating variables into the string, so what it really saw was this:
echo $arr[3], "[4]";
But, doing
echo "{$arr[3][4]}";
forces PHP to treat everything inside the braces as a variable reference, and you end up with the expected Hi there.
They tell the parser, where a variable name starts and ends. In this particular case it might not be needed, but consider this example:
$this->$toShow[0]
What should the parser do? Is $toShow an array or $this->$toShow ? In this case, the variable is resolved first and the array index is applied to the resulting property.
So if you actually want to access $toShow[0], you have to write:
$this->{$toShow[0]}
These curly braces can be used to use expressions to specify the variable identifier instead of just a variable’s value:
$var = 'foo';
echo ${$var.'bar'}; // echoes the value of $foobar
echo $$var.'bar'; // echoes the value of $foo concatenated with "bar"
$this->{$toShow}();
Break it down as below:
First this is a object oriented programming style as you got to see $this and ->. Second, {$toShow}() is a method(function) as you can see the () brackets.
So now {$toShow}() should somehow be parsed to a name like 'compute()'. And, $toShow is just a variable which might hold a possible function name. But the question remains, why is {} used around.
The reason is {} brackets substitues the value in the place. To clarify,
$toShow="compute";
so,
{$toShow}(); //is equivalent to compute();
but this is not true:
$toShow(); //this is wrong as a variablename is not a legal function name

PHP: Access Array Value on the Fly

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.

Categories