PHP: get array element - php

Why does this code not work?
echo explode("?", $_SERVER["REQUEST_URI"])[0];
It says syntax error, unexpected '['.
Oddly, this works:
$tmp = explode("?", $_SERVER["REQUEST_URI"]);
echo $tmp[0];
But I really want to avoid to create such a $tmp variable here.
How do I fix it?
After the helpful answers, some remaining questions: Is there any good reason of the design of the language to make this not possible? Or did the PHP implementors just not thought about this? Or was it for some reason difficult to make this possible?

Unlike Javascript, PHP can't address an array element after a function. You have to split it up into two statements or use array_slice().

This is only allowed in the development branch of PHP (it's a new feature called "array dereferencing"):
echo explode("?", $_SERVER["REQUEST_URI"])[0];
You can do this
list($noQs) = explode("?", $_SERVER["REQUEST_URI"]);
or use array_slice/temp variable, like stillstanding said. You shouldn't use array_shift, as it expects an argument passed by reference.

It's a (silly) limitation of the current PHP parser that your first example doesn't work. However, supposedly the next major version of PHP will fix this.

Take a look at this previous question.
Hoohaah's suggestion of using strstr() is quite nice. The following will return from the beginning of the string until the first ? (the third argument for strstr() is only available for PHP 5.3.0 onward):
echo strstr($_SERVER["REQUEST_URI"], "?", TRUE);
Or if you want to stick with explode, you can make use if list(). (The 2 indicates that at most 2 elements will be returned by explode).
list($url) = explode("?", $_SERVER["REQUEST_URI"], 2);
echo $url;
Finally, to use the natively available PHP URL parsing;
$info = parse_url($_SERVER["REQUEST_URI"]);
echo $info["scheme"] . "://" . $info["host"] . $info["path"];

EDIT:
echo current(explode("?", $_SERVER["REQUEST_URI"]));

I believe PHP 5.4 comes with this feature, at long last. Sadly, it will be a while before your average web host updates their PHP version. My Ubuntu VPS doesn't even have it in the default repos.

Related

Does PHP 7 have an equivalent of array_value_last()?

This is genuine question (but also code golf for PHP devs).
I know array_key_last() exists in PHP.
I would like to use array_value_last() on explode('/', __FILE__) but... array_value_last() doesn't exist.
I am working inside a constrained environment (an included file which contains and runs a function, before returning data) and I have tried both:
array_pop(explode('/', __FILE__))
end(explode('/', __FILE__))
and neither of these work. (I don't know why they are not working).
N.B. The sole purpose of the environment is to return a variable (either an array or a string). In this environment array_pop(explode('/', __FILE__)) and end(explode('/', __FILE__)) both result in a browser error: Content Encoding Error An error occurred during a connection to example.com. Please contact the website owners to inform them of this problem.
Statements such asechoand other executing statements produce the same Encoding Error.
Here is my current code, which is working:
$My_Filename = explode('/', __FILE__)[(count(explode('/', __FILE__)) - 1)];
Is there a shorthand in PHP 7 to get the last value of an array?
You could do it with end
$latestValue = end($array); // Returns latest value in $array, setting the internal pointer to the last element
reset($array); // Don't forget to reset the pointer!!!
Ok... if it doesn't work (that's very strange dude, big problem xD) you could try something like:
$aux = array_values($array); //No need to use this if it isn't an associative array
$size = count($aux);
$latestValue = $array[$size-1]; //Be careful with empty arrays
You can use basename(__FILE__); to get last part of the path. In general don't strive for this kind of one-liners - you won't gain anything in terms of performance, but loose code readability.
Both array_pop() and end() functions with expressions will give you a notice, because they will also try to modify variable (passed by reference) in current scope, and the message you get is coming from server or error handler (hidden details in production environment) - default interpreter display (better for dev) would give you: <b>Notice</b>: Only variables should be passed by reference in....
Here's a possible candidate for the code golf:
Original: explode('/', __FILE__)[(count(explode('/', __FILE__)) - 1)] // 59 characters
Alternative: array_reverse(explode('/', __FILE__))[0] // 40 characters
That represents a reduction of nearly 33%.
I'm curious to know if there might be an even better shorthand.

str_replace: Replace string with a function

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().

php explode / split - co-existence in single script

I have php two servers with different versions of php,
and am having trouble with split statement which seems to be deprecated on new box.
I replaced with explode which is not known to old box.
$connect = explode(";", DB_CONNECT);
$connect = split(";", DB_CONNECT);
what statement(s) will make both servers happy?
Upgrading is not an option tonight.
A better option in the short term is to disable the warning until you're able to upgrade your PHP version.
See: http://php.net/manual/en/function.error-reporting.php
If explode doesnt exist, create it
if (!function_exists('explode')) {
function explode($str, $array) {
return split($str, $array);
}
}
Try preg_split() and preg_match_all(). The latter doesn't return an array, but may fill in an array pass in as third argument.
I have not tried this but hopefully it will work. Good luck.
function ultraExplode($del,$arr){
$ver=phpversion();
if ($ver>=5) return explode($del,$arr);
else return split($del,$arr);}

explode without variables [duplicate]

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

What does a . (dot) do in PHP?

What does the following command do in PHP?
. $string // ($string is something which I declared in the program)
On its own, that does nothing at all (it's not valid syntax). However, if you have something like this:
<?php
$string1 = "Hello ";
$string2 = "world!";
$string = $string1 . $string2;
echo $string;
?>
You will see Hello world!. The . is the string concatenation operator.
Taken alone, this is a syntax error. The dot . is the concatenation operator that converts its arguments to strings and concatenates them. For example,
<?php
$string = "x";
$s = 42 . $string;
// $s is now "42x"
Your statement would throw back an error.
The "dot" is a string concatenator. That is, it helps you to combine strings together into another string.
Example.
$full = $part1 . $part2;
Concerning getting started: That's a difficult question. PHP.NET will be your functional looking site. Google-ing just about anything on PHP will direct you there. I'd look at getting a localhost setup of PHP/MySQL/Apache. If you're on a Windows machine, you can get a WAMP server setup.
http://www.wampserver.com/en/
This will drastically speed up your development and testing time. Don't try to FTP everything up to a Web server, as this approach will waste away 10-15% of your working time. Work smart - work local.
Find an existing project (Open Source) with a great community and just try to start something. For example, I recently created DogFriendlyOlrando.com based on WordPress. I was curious as to the abilities of WordPress. It was a fun little project and gave me a good understanding of WordPress' capabilities. You'll learn the most from just diving in and doing. Good luck!
Two string operators are available. The first is the concatenation operator ('.') that returns its right and left argument concatenation.
Second is the concatenation operator of assignment ('.='), which adds the right-hand argument to the left-hand argument. For further details, please read Assignment Operators
The output is displayed directly to the browser like as a given below:
. $string // ($string is something which I declared in the program)

Categories