Get an array from URL - php

I have a URL in this format:
https://www.example.com/page?=item1&item2&item3&item4&item5
I need to put each item into a variable, likes this:
$var1 = item1;
$var2 = item2;
$var3 = item3;
$var4 = item4;
$var5 = item5;
It does not actually say item1, item2 etc in the URL, their actual values are different every time.
Does anyone know how to do this?
Thanks!

The URL Query String / GET-Parameters
Your example URL https://www.example.com/page?=item1&item2&item3&item4&item5 is malformed. The query string starting after the question mark ? is parsed with the format:
name1=value1&name2=value2...
Your URL means:
<empty name> = item1
item2 = ''
item3 = ''
...
Empty names are ignored when PHP parses GET-parameters.
Let's assume you have an URL https://www.example.com/page?item1&item2&item3&item4&item5 instead. (Note the remove =.)
Accessing GET-Parameters
If the given URL is the one of you PHP current script, you can easily access the GET-parameter using the preinitialized global variable $_GET. Try var_dump($_GET) and you get:
array (size=5)
'item1' => string '' (length=0)
'item2' => string '' (length=0)
'item3' => string '' (length=0)
'item4' => string '' (length=0)
'item5' => string '' (length=0)
As you can see, item1...item5 are the keys of the associative array, each with an empty string '' as the default value since you did not set any by item1=the+item.
Get The Keys as Array
To get closer to your needs specified in the title of your question, you can extract the keys using array_keys:
$url_keys = array_keys($_GET);
Now you have an array like this:
array (size=5)
0 => string 'item1' (length=5)
1 => string 'item2' (length=5)
2 => string 'item3' (length=5)
3 => string 'item4' (length=5)
4 => string 'item5' (length=5)
Extracting as Variables
I do not recommend to extract any changing data structures into your variable scope. Be aware that the client could even manipulate the request sending you something you do not expect. It is hard to find variable names when you do not exactly know what you get. Prefer to operate on arrays.
However, if you really need to import the keys into your variables scope, here are the ways how you can achieve that. PHP does provide a function extract that can do that in several ways. We want to use the numeric indexes with a prefix to become the variable names:
extract(array_keys($_GET), EXTR_PREFIX_ALL, 'var');
The result will be:
$var_0 = item1,
$var_1 = item2
The zero-based numbering is due to the fact, that arrays are nubered zero-based by default, so the returned array from the function array_keys.
To get the numbering as illustrated in your question, you can also renumber the array of keys.
extract(array_combine(range(1, count($_GET)),array_keys($_GET)), EXTR_PREFIX_ALL, 'var');
If you are bothered by the underscore within the names, you can also extract the keys using dynamic variable creation in a fairly simple loop:
foreach (array_keys($_GET) as $k => $v)
${'var'. ($k+1)} = $v;
When you want global variables instead, use
foreach (array_keys($_GET) as $k => $v)
$GLOBALS['var'. ($k+1)] = $v;
Extract Keys from Arbitrary URL
If you have to analyze a URL string from somewhere, you can use the parse_url function to extract the query first and then use parse_str which parses a query in the same way as PHP does automatically with the script's URL when building the $_GET associative array on startup.
parse_str(parse_url($url, PHP_URL_QUERY), $params);
$params is now
array (size=5)
'item1' => string '' (length=0)
'item2' => string '' (length=0)
'item3' => string '' (length=0)
'item4' => string '' (length=0)
'item5' => string '' (length=0)
You can handle that in the same way as shown above with the $_GET array.

You could try this
$var1 = $_GET['item1'];
$var2 = $_GET['item2'];
$var3 = $_GET['item3'];
$var4 = $_GET['item4'];
$var5 = $_GET['item5'];
All your URL variables are stored in the GET array

I am not sure about your URL format...
However, as already answered here, you can extract each parameter (if specified by name) using $_GET['item1'] etc...
And, if there some other format or Unknown number of values, you can work over the whole URL by getting it using $_SERVER['REQUEST_URI'] which will give the string:
/page?=item1&item2&item3&item4&item5
then, splitting that string with seperator &, assuming every splitted substring is a value of an item in the array (?) in the URL.

As you say, you want to get all parameters in your URL.
Actually, $_GET is already an array that you also can use. But when you want to create your own array / variable list, that is also possible.
To do that, you can use the super global $_GET, this is an array with every URL parameter in it.
For example, I made this code for you
<?php
$return = [];
foreach($_GET as $key => $value) {
$return[$key] = $value;
}
var_dump($_GET);
var_dump($return);
?>
When I visit the page (http://example.com/temp.php?a&b), it will result in
array(2) { ["a"]=> string(0) "" ["b"]=> string(0) "" } array(2) { ["a"]=> string(0) "" ["b"]=> string(0) "" }
As you can see, this has the same data. And, because you say that the values and maybe also the keys (file.php?key=value) can be diffrent, I recommend you to use the array.
So, you can also save them in formats like JSON, to easilly save the in the database, so you can use the afterwards.
When I use json_encode on one of the arrays it gives me a string that you can use.
{"a":"","b":""}
With json_decode you can change it back to the array

Related

Explode string with two different separators to create multidimensional array

I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!
Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.
It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507
you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!
There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));

multidimensional array with only one value, how to get properly the value?

I work with a CMS (Drupal 8). It automatically generates some multidimensional array with an unique value, like this :
//var_dump of my $array
array (size=1)
0 =>
array (size=1)
'value' => string '50' (length=2)
To date, I use this ugly way for automatically get the value (in example : "50") of these arrays :
array_shift(array_values(array_shift(array_values($array))))
My question is, is there a better way in php for get that ?
So you know it's an array in an array?
$value = reset(reset($array));
You don't know how many turtles arrays are nested?
$value = $array;
while(is_array($value))
$value = reset($array);
Docs on reset
Just use via index:
$array[0]['value']

PHP - retrieving and parsing this JSON file

I'm looking for a way to access this JSON file data. What I'm interested in is to extract the property named documentjsonblob, as below.
object(Quadrem\Model\Order)[201]
protected '_dateCreated' => null
protected '_buyerCode' => null
array (size=2)
2415 =>
array (size=23)
'#storeid' => string '813' (length=3)
'#active' => string '1' (length=1)
'#created' => string '2013-11-25 12:28:21' (length=19)
'documentjsonblob' => string '{"HEAD":{"ORDERSEQUENCE":"0","TOTAL_TAX":7.9,"TOTAL_AMOUNT":86.9,"NUMBER":"AKMon3","TYPE":"NB","TYPE_NAME":"Standard PO","SUPPLIER":"0000002122","CREATED":"2013-04-29T12:00:00Z","CONTRACT_NUMBER":"","EXTERNAL_REFERENCE":"","CONTACT_PERSON":"Caroline Howlett","COMMENT":[""],"CURRENCY":"AUD","DELIVERY_TERMS":"DeliveryCondition|","PAYMENT_TERMS":[{"TEXT1":"21st day of next month after receipt"}],"NET_VALUE":79.0,"DELIVERY_ADDRESS":{"NAME_1":"KGTP FACILITY","NAME_2":"GAS TREATMENT PLANT","NAME_3":"KGPF","POSTAL_CODE":"6714","CITY":"Karratha","STREET":"Withnell Bay","REGION":"AUWA","REGION_NAME":"AUWA","COUNTRY":"AU"}]}' (length=3029)
'documenttype' => string 'PO' (length=2)
1890 =>
array (size=23)
'#storeid' => null
'#active' => null
I'm not quite sure which kind of an encoded JSON file this is by the way it looks. Would appreciate it if somebody could help.
Thanks.
Since in the comment you have mentioned it is the out put of var_dump and you want to get documentjsonblob, let's follow this:
On first line you have object(Quadrem\Model\Order)[201], that means you var_dumped an object, say $my_obj
On line four array (size=2) says you have an array, and what you need is located in the first element of the array, so $my_obj[0]
$my_obj[0] holds an associative array, and the desired index is documentjsonblob, so we can get the String representation as:
$my_arr = $my_obj[0];
$json_str = $my_arr['documentjsonblob'];
Now $json_str holds the String representation, to convert it to an PHP object:
$json_obj = json_decode($json_str);
So now $json_obj holds the object you want.

Accessing Multi dimensional array object in PHP

I have an item object in PHP, which has the following structure on var_dump :
$item->properties:
array (size=1)
1 =>
array (size=4)
'Key1' => string 'Value1' (length=6)
'Key2' => int 1
'Key3' => string 'true' (length=4)
'Key4' => string 'true' (length=4)
I want to access Key, value in a foreach loop and assign Key, value pair to some internal variables, however when i am using the foloowing code to loop pver array of array, i am getting error in accessing the values in the way i want. Here is what i am doing :
foreach($item->properties as $property) {
foreach($property as $value) {
echo $value;
}
}
Anyone have an idea what am i doing wrong, and how can i fix that ?
one of the things you provide to the foreach isn't a a valid argument, as the error says. Find out which of the 2 it is (linenumber) and var_dump that argument to see what type it is (probably "not an array" ).
In the end either $item->properties itself, or the array values of that array (if it is one), so $property is not an array.
It could be, for instance, that maybe the first key of the properties IS an array, but the second isn't? then you could use is_array to check.

Parsing HTTP data into PHP variables

I have a reasonably large number of variables encoded in the form:
foo=bar&spam[eggs]=delicious&...
These are all in a single string (eg, $data = "foo=bar&spam[eggs]=delicious&..."). The variables are arbitrarily deeply nested -- easily four or five levels deep ("spam[eggs][bloody][vikings]=loud").
Is there an easy, reliable way to get a multi-dimensional PHP array from this? I assume PHP has a parser to do this, though I don't know if it's exposed for my use. Ideally, I could do something like:
// given $data == "foo=bar&spam[eggs]=delicious"
$arr = some_magical_function( $data );
/* arr = Array
(
[foo] => bar
[spam] => Array
(
[eggs] => delicious
)
)
*/
If your string is in URI params format, parse_str is the magic function you are looking for.
You might want to take a look at parse_str ; here's an example :
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
And, with your input :
$str = 'oo=bar&spam[eggs]=delicious&spam[eggs][bloody][vikings]=loud';
$output = array();
parse_str($str, $output);
var_dump($output);
You'll get this :
array
'oo' => string 'bar' (length=3)
'spam' =>
array
'eggs' =>
array
'bloody' =>
array
'vikings' => string 'loud' (length=4)
Which should be what you want ;-)
(notice the multi-level array ; and the fact that ths first spam[eggs] has been overriden by the second one, btw)
If your data comes from the request uri, use $_GET

Categories