Can I generate an array based on url path? - php

I have a path like:
/blog/2/post/45/comment/24
Can I have an array depends on what I have on url, like :
$arr = array('blog'=>'2','post'=>'45','comment'=>'24');
But it should depend on variable passed:
/blog/2 should produce $arr = array('blog'=>'2');
Is this possible to create dynamic array?

You could try something like this:
function path2hash($path) {
// $path contains whatever you want to split
$chunks = explode('/', $path);
$result = array();
for ($i = 0; $i < sizeof($chunks) - 1; $i+=2)
$result[$chunks[$i]] = $chunks[$i+1];
return $result;
}
You could then use parse_url to extract the path, and this function to turn it into the desired hash.

First use $_SERVER['REQUEST_URI'] to find the current path.
now, you can use explode and other string functions to produce the array...
If you need a working example, Ill try and post one.
EDIT:
$path=explode('/',$path);
$arr=array(
$path[0]=>$path[1],
$path[1]=>$path[2]);
or don't know how long it is...
$arr=array();
for ($i=0; $i+1<count($path);i+=2)
$arr[$path[$i]]=$path[$i+1];

Here's a simple example trying to solve the issue. This will put the arguments in the "arguments" array, and will contain each combination of key/value in the array. If there's an odd number of arguments, the last element will be ignored.
This uses array_shift() to remove the first element from the array, which then is used as a key in the arguments array. We then remove the next element from the array, yet again using array_shift(). If we find an actual value here (array_shift returns NULL when the array is empty), we create a entry in the arguments array.
$path = '/blog/2/post/45/comment/24';
$elements = explode('/', $path);
// remove first, empty element
array_shift($elements);
$arguments = array();
while($key = array_shift($elements))
{
$value = array_shift($elements);
if ($value !== NULL)
{
$arguments[$key] = $value;
}
}

Not really an answer per se but you may find http://www.php.net/manual/en/function.parse-url.php useful.

Related

How to translate multiple parameters to a PHP conditional if statement

Let's say I have the following url: example.php?grab=1,3&something=...
grab has two values, how can I translate that to a conditional if statement.
For example, if count is a variable and you want to calculate if count is equal to one of the grab values.
$grab = $_GET["grab"];
$count = 4;
if($count == $grab(values)) {
alert("True");
}
If its always going to be , that glues the values, just explode them, that turns them into an array. Then just use your resident array functions to check. In this example, in_array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
$pieces = explode(',', $grab);
if(in_array($count, $pieces)) {
// do something here if found
}
}
Sidenote: If you try to devise your url to be like this:
example.php?grab[]=1&grab[]=3&something
You wouldn't need to explode it at all. You can just get the values, and straight up use in_array.
The example above grab already returns it an array:
if(!empty($_GET['grab'])) {
$grab = $_GET["grab"];
$count = 4;
if(in_array($count, $grab)) {
// do something here if found
}
}
Method#1: Reformat URL and Use PHP in_array()
Why not reformat your url to something like this: example.php?grab[]=1&grab[]=3&something=... which automatically returns the grab value as an array in PHP?
And then do something like:
if(isset($_GET['grab']) && in_array(4, $_GET['grab'])) {
// do something
}
Method#2: Split String into Array and Use PHP in_array()
If you do not wish to reformat your url, then simply split the string into an array using php's explode function and check if value exists, for example:
if(isset($_GET['grab'])) {
$grab_array = explode(",", $_GET['grab'])
if(in_array(4, $grab_array)) {
// do something
}
}
Method#3: Use Regular Expressions
You could also use regular expressions to check for a match.

How to export each subarrays as an array in PHP

is it possible that, get arrays to $value with key:
Example:
$array = Array("one"=>Array("field1"=>"value1","field2"=>"value2"),
"two"=>Array("field3"=>"value3","field4"=>"value4"));
Export arrays to value:
$first = any_main_php_function_name(0,$array);
$second = any_main_php_function_name(1,$array);
Result:
$first = Array("field1"=>"value1","field2"=>"value2");
$second = Array("field3"=>"value3","field4"=>"value4");
Basically, I wanna extract multiple array. If there is no such function (any_main_php_function_name) in PHP so How can i extract above $array.
You don't need any funtion to do that. Simply get subarrays like this:
$first = $array['one'];
$second = $array['two'];
Unless you don't know the one,two keys, then you can use array_shift to get first item (one subarray). Remember that this functions also removes returned value from root array.
array_slice does what you want
$first = array_slice($array, 0, 1);
$second = array_slice($array, 1, 1);
print_r($first);
print_r($second);
May be you can array_shift to get the element from array, Like this:
$first_element=array_shift($array);
Make sure it only removes the first element from the array and
return the value of removed element.
And if you don't want to remove the element or get the sub-array in any sequence, then you can create a function like this,
function myFunction($index,$array) {
$keys = array_keys($array);
$sub_array=$arr[$keys[$index]];
}
In above function we just get the keys in a array and then use the known index to get the sub-array using keys array.
Please check this
foreach($array["one"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}
foreach($array["true"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}

Key Value Array From String

I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);
This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:
$MyArray = array('Type'=>'Honda', 'Color'=>'Red');
But my probem is that the the data is already in the form of a string. Thank you for any help.
There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.
An example specification for the custom function:
Use explode() to split each element based on the comma.
Iterate over the result and:
explode() on =>
Remove unnecessary characters, i.e. single quotes
Store the first element as the key and the second element as the value
Return the array.
Note: if your strings contain delimiters this will be more challenging.
You do need to "take them out of the string", as you say. But you don't have to do it manually. The other answer uses explode; that's a fine method. I'll show you another - what I think is the easiest way is to use preg_match_all() (documentation), like this:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$array = array();
preg_match_all("/'(.+?)'=>'(.+?)'/", $string, $matches);
foreach ($matches[1] as $i => $key) {
$array[$key] = $matches[2][$i];
}
var_dump($array);
You need to parse the string and extract the data:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$elements = explode(",",$string);
$keyValuePairs = array();
foreach($elements as $element){
$keyValuePairs[] = explode("=>",$element);
}
var_dump($keyValuePairs);
Now you can create your on array using the $keyValuePairs array.
Here is an example of one way you can do it -
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$realArray = explode(',',$Array); // get the items that will be in the new array
$newArray = array();
foreach($realArray as $value) {
$arrayBit = explode('=>', $value); // split each item
$key = str_replace('\'', '', $arrayBit[0]); // clean up
$newValue = str_replace('\'', '', $arrayBit[1]); // clean up
$newArray[$key] = $newValue; // place the new item in the new array
}
print_r($newArray); // just to see the new array
echo $newArray['Type']; // calls out one element
This could be placed into a function that could be extended so each item gets cleaned up properly (instead of the brute force method shown here), but demonstrates the basics.

How to use string values from one array as indexes for another array in PHP

I've splitted a string into array, giving a delimitator. So, this new array created, will contain values that I would want to use as indexes for another given array.
Having a situation like this:
// my given array
$array['key1']['key2']['a_given_key']['some_other_given_key'] = 'blablabl';
// the value of my given array
$value = $array['key1']['key2']['a_given_key']['some_other_given_key'];
$string = "key1;key2";
$keys = explode(";", $string);
I want to call dinamically (during the execution of my PHP script) the value of the given array, but, using as indexes all the values of the array $keys, and in addition appending the indexes ['a_given_key']['some_other_given_key'] of my given array.
I hope I have been clear.
Many thanks.
To make it work you have to use references. Below code should work as you expect:
<?php
$string = "key1;key2;key3;key4";
$keys = explode(";", $string);
$array['key1']['key2']['key3']['key4']['a_given_key']['some_other_given_key'] = 'blablabl';
$ref = & $array;
for ($i=0, $c = count($keys); $i<$c ; ++$i) {
$ref = &$ref[$keys[$i]];
}
echo $ref['a_given_key']['some_other_given_key'];
$value = $ref['a_given_key']['some_other_given_key'];
echo $value;
?>
I would like to add that just after using reference you should unset it using:
unset($ref);
If you don't do this and many lines later you run for example $ref = 2; it will modify your source array so you have to remember about unsetting references just after it's no longer in use.

Getting element from PHP array returned by function

I'm not sure if this is possible, but I can't figure out how to do it if it is...
I want to get a specific element out of an array that is returned by a function, without first passing it into an array... like this...
$item = getSomeArray()[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
What's the correct syntax for this?
PHP cannot do this yet, it's a well-known limitation. You have every right to be wondering "are you kidding me?". Sorry.
If you don't mind generating an E_STRICT warning you can always pull out the first and last elements of an array with reset and end respectively -- this means that you can also pull out any element since array_slice can arrange for the one you want to remain first or last, but that's perhaps taking things too far.
But despair not: the (at this time upcoming) PHP 5.4 release will include exactly this feature (under the name array dereferencing).
Update: I just thought of another technique which would work. There's probably good reason that I 've never used this or seen it used, but technically it does the job.
// To pull out Nth item of array:
list($item) = array_slice(getSomeArray(), N - 1, 1);
PHP 5.4 has added Array Dereferencing,
here's the example from PHP's Array documentation:
Example #7 Array dereferencing
function getArray() {
return ['a', 'b', 'c'];
}
// PHP 5.4
$secondElement = getArray()[0]; // output = a
// Previously
$tmp = getArray();
$secondElement = $tmp[0]; // output = a
The syntax you're referring to is known as function array dereferencing. It's not yet implemented and there's an RFC for it.
The generally accepted syntax is to assign the return value of the function to an array and access the value from that with the $array[1]syntax.
That said, however you could also pass the key you want as an argument to your function.
function getSomeArray( $key = null ) {
$array = array(
0 => "cheddar",
1 => "wensleydale"
);
return is_null($key) ? $array : isset( $array[$key] ) ? $array[$key] : false;
}
echo getSomeArray(0); // only key 0
echo getSomeArray(); // entire array
Yes, php can't do that. Bat you can use ArrayObect, like so:
$item = getSomeArray()->{1};
// Credits for curly braces for Bracketworks
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return new ArrayObject($ret, ArrayObject::ARRAY_AS_PROPS);
}
Okay, maybe not working with numeric keys, but i'm not sure.
I know this is an old question, but, in your example, you could also use array_pop() to get the last element of the array, (or array_shift() to get the first).
<?php
$item = array_pop(getSomeArray());
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
As the others says, there is no direct way to do this, I usually just assign it to a variable like so:
$items = getSomeArray();
$item = $items[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
I am fairly certain that is not possible to do in PHP. You have to assign the returned array to another array before you can access the elements within or use it directly in some other function that will iterate though the returned array (i.e. var_dump(getSomeArray()) ).

Categories