Как передать метод get в ссылку
Ну так просто в параметр передайте значение.
А на странице уже работайте с ним.
Отслеживать
ответ дан 17 фев 2020 в 15:20
Denis640Kb Denis640Kb
14k 5 5 золотых знаков 22 22 серебряных знака 46 46 бронзовых знаков
- php
- php7
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.15.1019
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Получить GET-параметр из URL
Иногда нужно быстро получить GET-параметр из строки с URL, в этом поможет PHP функция parse_url() .
$url = 'http://site.ru/path?email=mail@site.ru&name=site'; $parts = parse_url($url); parse_str($parts['query'], $query); // Все GET-параметры print_r($query); // Параметр «email» echo $query['email'];
Для частого использования лучше применять функцию:
function getUrlQuery($url, $key = null) < $parts = parse_url($url); if (!empty($parts['query'])) < parse_str($parts['query'], $query); if (is_null($key)) < return $query; >elseif (isset($query[$key])) < return $query[$key]; >> return false; > // Все GET-параметры $data = getUrlQuery('http://site.ru/path?email=mail@site.ru&name=site'); print_r($data); // Параметр «email» echo getUrlQuery('http://site.ru/path?email=mail@site.ru&name=site', 'email');
Результат:
Array( [email] => mail@site.ru [name] => site ) mail@site.ru
Как передать get параметры в Url?
Как передать get параметры в Url, если я не использую форму и ссылки?
- Вопрос задан более трёх лет назад
- 16737 просмотров
Комментировать
Решения вопроса 1

Ответ написан более трёх лет назад
Нравится 2 3 комментария
Александр @Sentim Автор вопроса
Как мне получить такой(mysite.ru/?a=2&b=3) url? я же не буду руками его прописывать.

Александр @Sentim Автор вопроса
Александр Рябов: Спасибо за помощь.
Ответы на вопрос 0
Ваш ответ на вопрос
Войдите, чтобы написать ответ

- JavaScript
- +2 ещё
Не работает скрипт npm run, что делать?
- 1 подписчик
- только что
- 3 просмотра

- JavaScript
- +1 ещё
Как объеденить круговой слайдер(диапозон) с полем ввода и кнопками + и -?
- 1 подписчик
- 2 часа назад
- 20 просмотров

- JavaScript
- +1 ещё
Почему не выполняется функция в React.js из библиотеки WebTorrent?
- 1 подписчик
- 5 часов назад
- 40 просмотров

- PHP
- +2 ещё
Как вывести полное описание товара в категории Woocommerce?
- 1 подписчик
- 8 часов назад
- 17 просмотров

- JavaScript
Параметры функцийв JS?
- 1 подписчик
- 9 часов назад
- 66 просмотров

- PHP
Не получается сделать чтобы форма регистрации передавала данные в БД, как правильно это сделать и что заменить?
- 1 подписчик
- 9 часов назад
- 36 просмотров

- PHP
Не получается сделать чтобы форма регистрации передавала данные в БД, как правильно это сделать и что заменить?
- 1 подписчик
- 10 часов назад
- 58 просмотров

- HTML
- +1 ещё
Как пофиксти проблему с амперсантом?
- 1 подписчик
- 10 часов назад
- 54 просмотра

- HTML
- +2 ещё
Подобное поведение норма?
- 1 подписчик
- 12 часов назад
- 103 просмотра

- HTML
- +3 ещё
Почему не работает переход на страницу?
- 1 подписчик
- 13 часов назад
- 107 просмотров
от 200 000 до 600 000 ₽
Zaymigo • Нижний Новгород
от 180 000 ₽
20 нояб. 2023, в 09:22
50000 руб./за проект
20 нояб. 2023, в 07:54
13000 руб./за проект
20 нояб. 2023, в 07:06
20000 руб./за проект
Минуточку внимания
Присоединяйтесь к сообществу, чтобы узнавать новое и делиться знаниями
- Как перенести описание вниз?
- 2 подписчика
- 0 ответов
- 2 подписчика
- 0 ответов
- 3 подписчика
- 2 ответа
- 2 подписчика
- 1 ответ
- 2 подписчика
- 2 ответа
- 2 подписчика
- 2 ответа
- 2 подписчика
- 4 ответа
- 2 подписчика
- 1 ответ
- 2 подписчика
- 2 ответа
- 2 подписчика
- 1 ответ
Как передать get параметр в ссылке php
beware unset() destroys references
$x = ‘x’;
change( $x );
echo $x; // outputs «x» not «q23» —- remove the unset() and output is «q23» not «x»2 years ago
I designed a class that can easily pass references.
#### Problem 1
function problem (& $value )
>
problem ( 1 ); // cannot be passed by reference#### Problem 2
class problem2
static function __callStatic ( $name , & $arguments ) // cannot take arguments by reference
>
>
?>My solution
class Reference
function __construct (public mixed & $data )
>#### Problem solving 1 ####
function test ( $value )
$value = & Reference :: get ( $value ); // values OR reference
$value = «test- $value » ;
return $value ;
>echo test ( 1 ), PHP_EOL ; // test-1
$val = 2 ;
echo test ( Reference :: create ( $val )), PHP_EOL ; // test-2
echo $val , PHP_EOL ; // test-2#### Problem solving 2 ####
class TestCall
static function __callStatic ( $name , $arguments )
$value = & Reference :: get ( $arguments [ 0 ]);
$value = » $name — $value » ;
return $value ;
>
>echo TestCall :: test ( 3 ), PHP_EOL ; // test-3
$val = 4 ;
echo TestCall :: test ( Reference :: create ( $val )), PHP_EOL ; // test-4
echo $val , PHP_EOL ; // test-48 months ago
Parameters passed by references can have default values.
You can find out if a variable was actually passed by using func_num_args():function refault ( & $ref = ‘Do I have to be calculated?’ ) echo ‘NUM ARGS: ‘ . func_num_args (). «\n» ;
echo «ORI VALUE: < $ref >\n» ;
if( func_num_args () > 0 ) $ref = ‘Yes, expensive to calculate result: ‘ . sleep ( 1 );
else $ref = ‘No.’ ;
echo «NEW VALUE: < $ref >\n» ;
>$result = ‘Do I have to be calculated?’ ;
refault ( $result );
echo «RESULT: < $result >\n» ;
// NUM ARGS: 1
// ORI VALUE: Do I have to be calculated?
// NEW VALUE: Yes, expensive to calculate result: 0
// RESULT: Yes, expensive to calculate result: 0refault ();
// NUM ARGS: 0
// ORI VALUE: Do I have to be calculated?
// NEW VALUE: No.
?>9 years ago
The notes indicate that a function variable reference will receive a deprecated warning in the 5.3 series, however when calling the function via call_user_func the operation aborts without fatal error.
This is not a «bug» since it is not likely worth resolving, however should be noted in this documentation.
4 years ago
Within a class, passing array elements by reference which don’t exist are added to the array as null. Compared to a normal function, this changes the behavior of the function from throwing an error to creating a new (null) entry in the referenced array with a new key.
class foo <
public $arr = [ ‘a’ => ‘apple’ , ‘b’ => ‘banana’ ];
public function normalFunction ( $key ) return $this -> arr [ $key ];
>
public function & referenceReturningFunction ( $key ) return $this -> arr [ $key ];
>
>$bar = new foo ();
$var = $bar -> normalFunction ( ‘beer’ ); //Notice Error. Undefined index beer
$var = & $bar -> referenceReturningFunction ( ‘beer’ ); // No error. The value of $bar is now null
var_dump ( $bar -> arr );
/**
[
«a» => «apple»,
«b» => «banana»,
«beer» => null,
],
*/?>
This is in no way a «bug» — the framework is performing as designed, but it took careful thought to figure out what was going on. PHP7.36 years ago
For anyone wondering, the copy-on-write behaviour just does the Right Thing™ when an array is passed to a function not by-ref which then passes it through to another function by-ref without writing to it. For example:
function do_sort (array $array ) : array usort ( $array , function ( $a , $b ) return strnatcasecmp ( $a [ ‘name’ ], $b [ ‘name’ ]);
>);var_dump ( $data );
do_sort ( $data ); // does not affect value of $data
var_dump ( $data );
$data = do_sort ( $data );
var_dump ( $data );11 years ago
This function internally swaps the contents between
two simple variables using ‘passing by reference’.Some programming languages have such a swap function
built in, but PHP seems to lack such a function. So,
one was created to fill the need. It only handles
simple, single variables, not arrays, but it is
still a very handy tool to have.No value is actually returned by this function, but
the contents of the indicated variables will be
exchanged (swapped) after the call.
*/$a = 123.456 ;
$b = ‘abcDEF’ ;print «
Define:\na = $a \nb = ' $b '
» ;
swap ( $a , $b );
print «After swap(a,b):\na = ' $a '\nb = $b
» ;
function swap (& $arg1 , & $arg2 )
// Swap contents of indicated variables.
$w = $arg1 ; $arg1 = $arg2 ; $arg2 = $w ;
>17 years ago
Some have noticed that reference parameters can not be assigned a default value. It’s actually wrong, they can be assigned a value as the other variables, but can’t have a «default reference value», for instance this code won’t compile :
function use_reference ( $someParam , & $param =& $POST )
.
>
?>But this one will work :
function use_reference ( $someParam , & $param = null )
?>So here is a workaround to have a default value for reference parameters :
$array1 = array ( ‘test’ , ‘test2’ );
$array [ $key ] = $val ;
>AddTo ( «indirect test» , «test» , $array1 );
AddTo ( «indirect POST test» , «test» );echo «Array 1 » ;
print_r ( $array1 );echo «_POST » ;
print_r ( $_POST );?>
And this scripts output is :
Array 1 Array
(
[0] => test
[1] => test2
[indirect test] => test
)
_POST Array
(
[indirect POST test] => test
)Of course that means you can only assign default reference to globals or super globals variables.
3 years ago
var_dump( $arr ); // [1, 2, 3]
If you changed a reference variable with a new `Address`, the variable it originally pointed to won’t change.
6 years ago
Beware of using references with anonymous function and «use» keyword :
If you have a PHP version between 5.3 and < 5.3.10, "use" keyword break the reference :
$arg = 1 ;
echo ‘withRef — BEFORE — ‘ . $arg . «\n» ; // 1
withRef ( $arg );
// in PHP 5.3 < 5.3.10 : display 1
// in PHP 5.3 >= 5.3.10 : display 2
echo ‘withRef — AFTER — ‘ . $arg . «\n» ;
?>A workaround is to use a copy of the reference variable in «use» keyword :
.
$arg2 = $arg ;
$func = function() use( $arg2 ) < /* do nothing, just declare using $arg2 */ >;19 years ago
Sometimes we need functions for building or modifying arrays whose elements are to be references to other variables (arrays or objects for instance). In this example, I wrote two functions ‘tst’ and ‘tst1’ that perform this task. Note how the functions are written, and how they are used.
array_push ( $arr , & $r );
// Alternatively, this also could be $arr[] = &$r (in this case)
>$arr0 = array(); // an empty array
$arr1 = array( 1 , 2 , 3 ); // the array to be referenced in $arr0// Note how we call the function:
tst ( $arr0 , & $arr1 ); // We are passing a reference to ‘$arr1’ in the call !print_r ( $arr0 ); // Contains just the reference to $arr1
array_push ( $arr0 , 5 ); // we add another element to $arr0
array_push ( $arr1 , 18 ); // we add another element to $arr1 as wellprint_r ( $arr1 );
print_r ( $arr0 ); // Changes in $arr1 are reflected in $arr0function tst1 (& $arr , & $r ) <
// Both arguments ‘$arr’ and ‘$r» are declared to be passed by
// reference,
// again, in the function’s body, we use a reference to
// the ‘$r’ argumentarray_push ( $arr , & $r );
// Alternatively, this also could be $arr[] = &$r (in this case)
>$arr0 = array(); // an empty array
$arr1 = array( 1 , 2 , 3 ); // the array to be referenced in $arr0// Note how we call the function:
tst1 ( $arr0 , $arr1 ); // ‘tst1’ understands ‘$r’ is a reference to ‘$arr1’print_r ( $arr0 ); // Contains just the reference to $arr1
array_push ( $arr0 , 5 ); // we add another element to $arr0
array_push ( $arr1 , 18 );print_r ( $arr1 );
print_r ( $arr0 ); // Changes in $arr1 are reflected in $arr0I hope this is somehow useful
