Jump to content

Building multidimensional array from url params


dangermark

Recommended Posts

Hi all,

 

I am trying to build a multidimensional array from values in a URL.

 

For example:

 

page.php?ind=123&loc=456&wt=789 needs to build the array like this:

Array 
( 
[0] => Array 
     ( 
     [0] => 123
     ) 
[1] => Array 
     ( 
     [0] => 456
     ) 
[2] => Array 
     ( 
     [0] => 789
     ) 
)

 

If one of these params is empty: page.php?ind=123&loc=&wt=789

 

I need the array to be

 

Array 
( 
[0] => Array 
     ( 
     [0] => 123
     ) 
[1] => Array 
     ( 
     [0] => 789
     ) 
) 

 

I am having some trouble wrapping my head around how to do this. I am using array_push to construct it, but i fear I may be missing something. There's a good change I am way off too :).  Any suggestions would be greatly appreciated.

 

My code:

 


<?php 

// get the id from the URL
if (isset($_GET['ind'])) {
$indId = $_GET['ind'];
}
if (isset($_GET['loc'])) {
$locId = $_GET['loc'];
}
if (isset($_GET['wt'])) {
$wtId = $_GET['wt'];
}

$searchArray = array();

if (!isset($_GET['ind'])) {
empty($_GET['ind');
} else {
array_push($searchArray, $ind);
}

if (!isset($_GET['loc'])) {
empty($_GET['loc']);
} else {
array_push($searchArray, $loc);
}

if (isset($_GET['wt'])) {
empty($_GET['wt']);
} else {
array_push($searchArray, $wt);
}

echo '<pre>';
print_r($searchArray);
echo '</pre>';

?>

Link to comment
Share on other sites

Here is how I would do it:

 

<?php 

$searchArray = array();

if (!empty($_GET['ind'])) {
array_push($searchArray, $_GET['ind']);
}

if (!empty($_GET['loc'])) {
array_push($searchArray, $_GET['loc']);
}

if (!empty($_GET['wt'])) {
array_push($searchArray, $_GET['wt']);
}

echo '<pre>';
print_r($searchArray);
echo '</pre>';

?>

 

The reason for using "not empty" instead of "isset" is that an empty variable is set, and you don't want an empty variable included in the array.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.