Showing posts with label PHP List. Show all posts
Showing posts with label PHP List. Show all posts

Friday, 2 August 2019

Getting Warning: split(): REG_BADRPT when using the split PHP function

Getting Warning: split(): REG_BADRPT when using the split PHP function when I try to split a string after each question mark (?).
E.g.
$string = "ABC?DEF?BGT";
list($a,$b) = split('?',$string);
Answer:
  • The reason why this is failing is split gives you the power to use regular expressions
  • Use the explode() function instead
  • If you really need to use the split() function try escaping the character eg. ‘/\?/’

Thursday, 25 September 2014

list in PHP

PHP list() function is utilized to allocate values to a list of variables as though they were an array.
The variables in PHP list() will be allocated to elements of the array in the request they were basically stored in the array.

Syntax:

list(var1,var2,...)
var : Required. The first variable to assign a value to
var : Optional. More variables to assign values to
Note : This function only works on numerical arrays.

Example:

<?php
$names = array( "Sam","Peter","Jack" );
list($s, $p, $j) = $names;
echo "I am $s, he is $p and he is $j.";
?>

O/P:

I am Sam, he is Peter and he is Jack.

Thursday, 4 September 2014

PHP: How would you return an array from a function in PHP?

If you have a function and you want to return multiple values from that function then you can easily return an array from the function. This is what it would look like:
function someFunc( ) {

$aVariable = 10;
$aVariable2 = 20;

return array($aVariable, $aVariable2);
}

How to retrieve the values returned from a function in PHP

You will probably want to retrieve the values returned from the function after you call it. What is the best way to do this? Well, there is actually a nice way to do this using the list function in PHP. Here is an example of how to retrieve the values returned from an array in a function – assuming that we are calling the same someFunc function that we showed above:
list($var1, $var2)  = 
     someFunc( ); 

//will print out values from someFunc
echo "$var1 $var2"; 

Now, $var1 and $var2 will hold the same values as $aVariable and $aVariable2 from the function someFunc.

Another option for retrieving the values returned from a function in PHP

Another possibility is to just store the return values in an array as well – here is an example:
$results = someFunc();

echo $results[0];

echo $results[1];
Note that in the example above everything returned from the call to someFunc is stored in the $results array – and the echo statements will output the values returned from someFunc.