Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

php - explode string into variables

Is there a way to explode a string into variables e.g

some_function($min, $max, "3, 20");

such that $min is assigned the value 3 and $max is assigned the value 20.

I know I can simply use

$data = explode("3, 20");

just wondering if there is another way.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP's language construct list() can perform multiple assignments to variables (or even other array keys) by assigning an array.

list($min, $max) = explode(",", "3,20");

However, you would still need to apply a trim() to your variables since the $max value would have a leading space, or replace explode() with preg_split('/s*,s*/', $string) to split it on commas and surrounding whitespace.

Note: Use caution with list() to be sure that the array you're assigning contains the same number of elements as list() has variables.

In PHP 5.x, when assigning a value directly to another array, as an element of that array, list() values are assigned from right to left in PHP 5.x, not left to right. In other words, you'll end up with array that is populated backwards (last value, first).

https://www.php.net/manual/en/migration70.incompatible.php

In PHP 7.x list() arguments are assigned from left to right, when assigning elements directly to an array. In other words, you'll end up with the first value as the first element in the recipient array.

<?php
    list($a[], $a[], $a[]) = [1, 2, 3];
    var_dump($a);
?>

PHP Manual

PHP 5.X Last value gets the first element position, but the recipient must an array (in this case $a, is the array)!

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

PHP 7.x First value becomes the first array element.

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

PHP Manual


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...