Link to home
Start Free TrialLog in
Avatar of peter-cooper
peter-cooper

asked on

How can I split a variable

Hello
I am assigning a variable from a $_GET like the code below. What returns is data in the format 'E-4-5-(5)'. I need to split this into just the 4 values because I need to insert into mysql but 4 seperate columns. Could they be split so I have 4 variables containg 1 value for each?

Example

Rack | Column | Row | Bay
E      4        5     5

Open in new window


$slot = $_GET['slot'];

Open in new window

Avatar of Dorababu M
Dorababu M
Flag of India image

As per the code here http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/

<?php
$str = "E-4-5-(5)";

$output = explodeX(Array("-","(",")"),$str);

foreach ($output as $o)

{

echo $o . "
";

}

function explodeX($delimiters,$string)

{

$return_array = Array($string); // The array to return

$d_count = 0;

while (isset($delimiters[$d_count])) // Loop to loop through all delimiters

{

$new_return_array = Array();

foreach($return_array as $el_to_split) // Explode all returned elements by the next delimiter

{

$put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);

foreach($put_in_new_return_array as $substr) // Put all the exploded elements in array to return

{

$new_return_array[] = $substr;

}

}

$return_array = $new_return_array; // Replace the previous return array by the next version

$d_count++;

}

return $return_array; // Return the exploded elements

}

Open in new window

Avatar of peter-cooper
peter-cooper

ASKER

@Dorababu All I get is white page. What I wanted to achieve was something like this;

$var1
$var2
$var3
$var4

Thanks
White page I have tested here http://phptester.net/. Result is as follows

User generated image
Well in my page it is white. Obviously something it doesn't like. What version of php foes explodeX use?
explodex is a custom function written it is not a built in function
All I get is white page.
That is usually a symptom of an undisclosed failure.  Turn on error_reporting(E_ALL) and check the error logs!

Please show us the exact GET request variables (these the URL arguments) so we can show you the exact way to access these programmatically, thanks.  This is called the SSCCE, and using the SSCCE is the key to getting good answers to technical questions.
I was thinking something like this, but this is not splitting to array

$edit = strtoupper($_POST['editslot']);
$array = preg_split("( - | - | - | ( | ) | )", $edit);
print_r($array);

Open in new window

You probably want something more like this, but it's a data-dependent problem.  We need to see the input data!  The code (especially code that does not work) is not useful here.  Just the before and after data, please.
<?php // demo/temp_peter_cooper.php
/**
 * https://www.experts-exchange.com/questions/29021097/How-can-I-split-a-variable.html
 *
 * Rack | Column | Row | Bay
 * E      4        5     5
 *
 * http://php.net/manual/en/function.explode.php
 * http://php.net/manual/en/function.trim.php
 */
error_reporting(E_ALL);


// MAYBE THIS IS FROM THE URL IN $_GET?
// INSERT CLEANUP AND SANITY CHECKS AS APPROPRIATE
$_GET['q'] = 'E-4-5-(5)';

// THESE ARE THE NAMES OF THE MATCHING DATA ELEMENTS
$vars = [ 'rack', 'column', 'row', 'bay' ];

// BREAK ON HYPHENS
$values = explode('-', $_GET['q']);

foreach ($values as $key => $value)
{
    $data[$vars[$key]] = trim($value, '()');
}

// SHOW THE WORK PRODUCT
var_dump($data);

// ASSIGN INDIVIDUAL VARIABLES
foreach ($data as $key => $value)
{
    $$key = $value;
}

// SHOW THE WORK PRODUCT
var_dump($rack, $column, $row, $bay);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Dorababu M
Dorababu M
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just a comment:

I would do the split in the front-end before sending the GET. This would minimize the roundtrips in a case of errors.
@Ray I tried your code but just white screen. I have posted complete code for you. Works fine without new code. Thanks ps. I stripped the comments for this excercise.

function box(){
	
	if ($_GET['activity'] == 'Box Destruction') {
		$id = $_GET['id'];
		$service = $_GET['service'];
		$activity = $_GET['activity'];
		$department = $_GET['department'];
		$company = $_GET['company'];
		$customerdest = $_SESSION['kt_login_id'];
		$item = $_GET['item'];
		$filebox = $_GET['filebox'];
		$user = $_GET['user'];
		$date = $_GET['date'];
		$address = $_GET['address'];
		$slot = $_GET['slot'];
		$reqdate = date('d/m/Y H:i:s');
		
		$vars = [ 'rack', 'column', 'row', 'bay' ];
		$values = explode('-', $slot);
		foreach ($values as $key => $value)
		{
                $data[$vars[$key]] = trim($value, '()');
		}
		
		var_dump($data);
		foreach ($data as $key => $value)
		{
                $$key = $value;
		}
		
		var_dump($rack, $column, $row, $bay);
		
		$query = "UPDATE `act` SET new = 0 WHERE id = '$id'";
		mysql_query($query) or die('Error' . $query .  'query failed');
		// update
		
		$query = "UPDATE `boxes` SET status = 3, destroyed_date=NOW(), destroyed_by='$user' WHERE department = '$department' AND customer = '$company' AND custref = '$item'";
		mysql_query($query) or die(mysql_error());
}

Open in new window

@Dorababu That works but how do i split to individual vars. thanks
If you know the value is fixed then you can assign them as follows after splitting

$var1 = $array[0]
$var2 = $array[1]
$var3 = $array[2]
$var4 = $array[3]

Open in new window

The script posted here has a parse error:
https://www.experts-exchange.com/questions/29021097/How-can-I-split-a-variable.html?anchorAnswerId=42124993#a42124993

You would not get a "white screen" from my code.  I tested it before I posted it.  You might have modified it?

Please, please please post the data!  Let us see the before and after.  We need to see your test case, and the expected outputs.  Show us the URL you use to access the test case, so we can see the request variables.
And now that I've looked at the code posted here, it appears that the code does not even use the variables you're asking about.

$_GET['slot'] get assigned to $slot
$slot gets converted into $data (an array)
$data gets expanded into four scalar variables: $rack, $column, $row, $bay

But none of $rack, $column, $row, $bay get used in the script.

Recommend you add error_reporting(E_ALL) to the top of the PHP scripts and fix anything that comes up in the messages.  If you've suppressed the messages, turn the messages back on or consult the error log.

Also, you really need to get off MySQL.  Code that uses MySQL is "living on borrowed time."  There is no supported version of PHP that still includes support for MySQL, so the matter is urgent.  Here is why you must make the change and detailed instructions about how to make the change.
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
@Dorababu Thanks that works. However, why would I get syntax error in mysql query and also, in error_log it says

Undefined variable: rack
Undefined variable: column
Undefined variable: row
Undefined variable: bay

Open in new window



<?php
$slot = $_GET['slot'];
$array = preg_split("/[-,(,)]+/", $slot);

$rack = $array[0];
$column = $array[1];
$row = $array[2];
$bay = $array[3];
		
	$query = "UPDATE `boxes` SET rack = '$rack', column = '$column', row = '$row', bay = '$bay', status = 3, destroyed_date=NOW(), destroyed_by='$user' WHERE department = '$department' AND customer = '$company' AND custref = '$item'";
	mysql_query($query) or die(mysql_error());
?>

Open in new window

Sorted it. column was causing the problem. Just amended like so `column` problem goes away.
Thanks very much for your help
peter-cooper you are welcome