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>';

?>

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.

That was exactly my problem; the array still being entered but empty.

 

Thanks a bunch for that, modified it slightly though to suit my 2 dimensional array:

 

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

 

Thanks a lot! Works perfectly.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.