I'm trying to extract some variables from my REQUEST_URI
:
liquidfinger.com/key1-value1/key2-value2/key3-value3
I want to transform these values into a php associative array. My code is as follows:
$pState = [];
$stateString = substr($_SERVER['REQUEST_URI'],1);//remove leading slash
if($stateString){
$statePairs = explode("/",$stateString);
foreach($statePairs as $statePair){
$statePairArray = explode("-",$statePair);
$pState[$statePairArray[0]] = $statePairArray[1];
}
}
The $pState
array is being created correctly and I can echo
all the keys and values. However, I am getting an error_log
:
Undefined offset: 1
I am even getting an error_log
when there are no key-value pairs, so the IF
statement shouldn't be executed, but possibly that is a characteristic of the error_log
?
Okay, just to recap, the code was working but I was getting error messages. Further tests yielded the following:
url: www.liquidfinger.com
print_r($pState): Array ( )
[11-Mar-2016 10:01:02 UTC] PHP Notice: Undefined offset: 1 in /home/adamglynsmith/public_html/index.php on line 20
url: http://www.liquidfinger.com/user-2/tab-browseAll/marker-101
print_r($pState): Array ( [user] => 2 [tab] => browseAll [marker] => 101 )
print_r($statePairArray): Array ( [0] => user [1] => 2 ) Array ( [0] => tab [1] => browseAll ) Array ( [0] => marker [1] => 101 )
[11-Mar-2016 10:14:41 UTC] PHP Notice: Undefined offset: 1 in /home/adamglynsmith/public_html/index.php on line 20
[11-Mar-2016 10:14:43 UTC] PHP Notice: Undefined offset: 1 in /home/adamglynsmith/public_html/index.php on line 20
Since I have spent quite enough time on it and since I ultimately wanted to end up with a JavaScript array, I solved - or avoided - the problem by using the php to construct a string for the JavaScript like so:
$stateString = str_replace("/","', ",$stateString);//get rid of slashes
$stateString = str_replace("-",":'",$stateString);//get rid of dashes
$stateString .= "'";//add final single quote
<script>
jState = {<?php echo $stateString; ?>};
</script>
Thanks.