John Davidson

PHP Variable assignment does not work as expected

0 comments
Message:


I am trying to assign parameters listed in the URL save into my variables. You can see the procedure here:


<?php

$browser;
$version;
$page;

foreach($_GET as $key => $value) {
if (strcmp($key, "browser")) {
$browser = $value;
}
elseif (strcmp($key, "version")) {
$version = $value;
}
elseif (strcmp($key, "page")) {
$page = $value;
}
}

echo $browser;
echo $version;
echo $page;
?>

But unfortunately, it only prints out the browser and the version. The page does not appear. Yes, the page parameter is definitely written correctly in the URL. If I change code like this, the variables get printed out correctly:


 <?php

foreach($_GET as $key => $value) {
if (strcmp($key, "browser")) {
echo $value;
}
elseif (strcmp($key, "version")) {
echo $value;
}
elseif (strcmp($key, "page")) {
echo $value;
}
}
?>

Link shematik: ./bglink/addstats.php?browser=Chrome&version=96&page=index

Thanks in advance.
Filip.



My Answer:
php
// Get the parameters from the URL
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];

// Check if the parameters are set
if(isset($param1) && isset($param2)) {
// Assign the parameters to variables
$variable1 = $param1;
$variable2 = $param2;

// Use the variables for further processing
echo "Variable 1: " . $variable1 . "
";
echo "Variable 2: " . $variable2 . "
";
} else {
echo "Parameters not set in the URL";
}


Make sure that the parameters `param1` and `param2` are passed in the URL in the following format: `http://example.com/script.php?param1=value1¶m2=value2`. If the parameters are not set in the URL, the script will output "Parameters not set in the URL".

Rate this post

4 of 5 based on 3000 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us