Here is what i have in php :
I need to do explode the given variable
$a = "hello~world";
I need to explode as
$first = "hello";
$second = "world";
How can i do this ??
Here is what i have tried so far.
<?php
$str = "a~b";
$a = (explode("~",$str));
$b = (explode("~",$str));
echo explode('.', 'a.b');
?>
I know i did wrong. What is my mistake and how can i fix this ?
If you know the number of variables you're expecting to get back (ie. 2 in this case) you can just assign them directly into a list:
list($first, $second) = explode('~', $a);
// $first = 'hello';
// $second = 'world';
Explode function will return an array with "explosed" elements
So change your code as follows (if you know that only two elements will be present)
list($a, $b) = explode('~', $str);
//You don't need to call explode one time for element.
Otherwise, if you don't know the number of elements:
$exploded_array = explode('~', $str);
foreach ($exploded_array as $element)
{
echo $element;
}
explode returns an array. explode will break the given string in to parts using given character(here its ~) and will return an array with the exploded parts.
$a = "hello~world";
$str_array = explode("~",$a);
$first = $str_array[0];
$second = $str_array[1];
echo $first." ".$second;
Your code should trigger a clear error message with debug information:
Notice: Array to string conversion
... on this line:
echo explode('.', 'a.b');
... and finally print this:
Array
I suppose you would not ignore this helpful information if you'd seen it so you've probably haven't configured your PHP development box to display error messages. The simplest way is, when installing PHP, to get your php.ini file by copying php.ini-development instead of php.ini-production. If you are using a third-party build, just tweak the error_reporting and display_errors directives.
As about the error, you have to understand that arrays are complex data structures, not scalar values. You cannot print an array as-is with echo. In the development phase you can inspect it with var_dump() (like any other variable).
Related
To get the right position I have to access in a tree array I'm working on a solution to bring an exploded string (with numeric keys, separated by "." (dot) - like in an register) to an array ...
$string = '1.3.2.5';
so the returning value should be an array with
$array[1][3][2][5] = 'x';
where x can hold any data or be empty
Here's a quick and dirty solution using eval(). I need to quote Rasmus Lerdorf here:
If eval() is the answer, you're almost certainly asking the wrong
question.
So, no, I am not happy with this answer, but it does work. Keep in mind that if the input comes from the users you might give them unwanted control over your server. It is very easy to do:
$test = 'x; rmdir($_SERVER["HOME"]);';. Do not use this on your server!
So be careful with this.
<?php
$string = '1.3.2.5';
$test = 'x';
$array = [];
function setArray($address,$value)
{
global $array;
eval('$array['.str_replace('.','][',$address).'] = $value;');
}
function getArray($address)
{
global $array;
eval('$value = $array['.str_replace('.','][',$address).'];');
return $value;
}
setArray($string,$test);
echo getArray($string);
echo '<pre>';
var_dump($array);
echo '</pre>';
Note that this will work with any address length > 1. Also note that you can overwrite a complete tree, accidentally, if you use a short address.
Who can find a good solution without eval()?
I've splitted a string into array, giving a delimitator. So, this new array created, will contain values that I would want to use as indexes for another given array.
Having a situation like this:
// my given array
$array['key1']['key2']['a_given_key']['some_other_given_key'] = 'blablabl';
// the value of my given array
$value = $array['key1']['key2']['a_given_key']['some_other_given_key'];
$string = "key1;key2";
$keys = explode(";", $string);
I want to call dinamically (during the execution of my PHP script) the value of the given array, but, using as indexes all the values of the array $keys, and in addition appending the indexes ['a_given_key']['some_other_given_key'] of my given array.
I hope I have been clear.
Many thanks.
To make it work you have to use references. Below code should work as you expect:
<?php
$string = "key1;key2;key3;key4";
$keys = explode(";", $string);
$array['key1']['key2']['key3']['key4']['a_given_key']['some_other_given_key'] = 'blablabl';
$ref = & $array;
for ($i=0, $c = count($keys); $i<$c ; ++$i) {
$ref = &$ref[$keys[$i]];
}
echo $ref['a_given_key']['some_other_given_key'];
$value = $ref['a_given_key']['some_other_given_key'];
echo $value;
?>
I would like to add that just after using reference you should unset it using:
unset($ref);
If you don't do this and many lines later you run for example $ref = 2; it will modify your source array so you have to remember about unsetting references just after it's no longer in use.
For example:
echo explode('#',$var); //but only echoing element 1 or 2 of the array?
Instead of:
$variable = explode('#',$var);
echo $variable[0];
Thank you.
On PHP versions that support array dereferencing, you can use the following syntax:
echo explode('#', $var)[0];
If not, you can use list():
list($foo) = explode('#', $var);
The above statement will assign the first value of the exploded array in the variable $foo.
Since PHP 5.4 you can write:
echo explode('#', $var)[0];
In earlier versions of PHP you can only achieve the behaviour with tricks:
echo current(explode('#', $var)); // get [0]
echo next(explode('#', $var)); // get [1]
Retreiving an element at an arbitrary position is not possible without a temporary variable.
Here is a simple function that can tidy your code if you don't want to use a variable every time:
function GetAt($arr, $key = 0)
{
return $arr[$key];
}
Call like:
echo GetAt(explode('#', $var)); // get [0]
echo GetAt(explode('#', $var), 1); // get [1]
Previous to PHP 5.4 you could do this:
echo array_shift(explode('#', $var));
That would echo the first element of the array created by explode. But it is doing so without error checking the output of explode, which is not ideal.
list can be used like this as well:
list($first) = explode('#', $var);
list(,$second) = explode('#', $var);
list(,,$third) = explode('#', $var);
Just use reset like this
echo reset(explode('#', $var));
I'm not sure if this is possible, but I can't figure out how to do it if it is...
I want to get a specific element out of an array that is returned by a function, without first passing it into an array... like this...
$item = getSomeArray()[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
What's the correct syntax for this?
PHP cannot do this yet, it's a well-known limitation. You have every right to be wondering "are you kidding me?". Sorry.
If you don't mind generating an E_STRICT warning you can always pull out the first and last elements of an array with reset and end respectively -- this means that you can also pull out any element since array_slice can arrange for the one you want to remain first or last, but that's perhaps taking things too far.
But despair not: the (at this time upcoming) PHP 5.4 release will include exactly this feature (under the name array dereferencing).
Update: I just thought of another technique which would work. There's probably good reason that I 've never used this or seen it used, but technically it does the job.
// To pull out Nth item of array:
list($item) = array_slice(getSomeArray(), N - 1, 1);
PHP 5.4 has added Array Dereferencing,
here's the example from PHP's Array documentation:
Example #7 Array dereferencing
function getArray() {
return ['a', 'b', 'c'];
}
// PHP 5.4
$secondElement = getArray()[0]; // output = a
// Previously
$tmp = getArray();
$secondElement = $tmp[0]; // output = a
The syntax you're referring to is known as function array dereferencing. It's not yet implemented and there's an RFC for it.
The generally accepted syntax is to assign the return value of the function to an array and access the value from that with the $array[1]syntax.
That said, however you could also pass the key you want as an argument to your function.
function getSomeArray( $key = null ) {
$array = array(
0 => "cheddar",
1 => "wensleydale"
);
return is_null($key) ? $array : isset( $array[$key] ) ? $array[$key] : false;
}
echo getSomeArray(0); // only key 0
echo getSomeArray(); // entire array
Yes, php can't do that. Bat you can use ArrayObect, like so:
$item = getSomeArray()->{1};
// Credits for curly braces for Bracketworks
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return new ArrayObject($ret, ArrayObject::ARRAY_AS_PROPS);
}
Okay, maybe not working with numeric keys, but i'm not sure.
I know this is an old question, but, in your example, you could also use array_pop() to get the last element of the array, (or array_shift() to get the first).
<?php
$item = array_pop(getSomeArray());
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
As the others says, there is no direct way to do this, I usually just assign it to a variable like so:
$items = getSomeArray();
$item = $items[1];
function getSomeArray(){
$ret = Array();
$ret[0] = 0;
$ret[1] = 100;
return $ret;
}
I am fairly certain that is not possible to do in PHP. You have to assign the returned array to another array before you can access the elements within or use it directly in some other function that will iterate though the returned array (i.e. var_dump(getSomeArray()) ).
So, I'm starting a new project and working with php for the first time.
I get that the average definition and functioning of arrays in php is actually pretty much a namevalue combo.
Is there some syntax, API, or other terminology for just a simple list of items?
I.e. inserting something like ['example','example2','example3','example4'] that I can just call based off their index position of the array, without having to go in and modify the syntax to include 0 => 'example', etc...
This is a very shortlived array so im not worried about long term accessibility
php arrays are simple to use. You can insert into an array like:
$array=array('a','b','c'.....);
Or
$array[]="a";
$array[]="b";
$array[]="c";
or
array_push($array, "a");
array_push($array, "b");
array_push($array, "c");
array_push($array, "d");
and call them by their index values:
$array[0];
this will give you a
$yourArray = array('a','b','c');
or
$yourArray[] = 'a';
$yourArray[] = 'b';
$yourArray[] = 'c';
will get you an array with integer index values instead of an associative one..
You still can use array as "classic" arrays in php, just the way you think.
For example :
<?php
$array = array("First", "Second", "Third");
echo $array[1];
?>
You can then add different values <?php $array[] = "Forth"; ?> and it will be indexed in the order you specified it.
Notice that you can still use it as an associative array :
<?php
$array["newValue"] = "Fifth";
$array[1] = "ReplaceTheSecond";
$array[10] = "";
?>
Arrays in PHP can either be based on a key, like 0 or "key" => "value", or values can just be "appended" to the array by using $array[] = 'value'; .
So:
$mine = array();
$mine[] = 'test';
$mine[] = 'test2';
echo $mine[0];
Would produce 'test';
Haven't tested the code.