I'm trying to use this cookie - current=["1","2","4"] - as a usable array in PHP.
At the moment I can echo these values, but can't use them as an array. How would I convert these values into a usable PHP array?
$currentUsers = $_COOKIE['current'];
echo $currentUsers;
print_r(array_values($currentUsers));
$array = explode(",",$currentUsers);
Var_dump($array);
Echo $array[0]; // 1
Echo $array[1]; // 2
Echo $array[2]; // 4
Edit: Not sure if the " is actually a part of the cookie values?
If it is you could use str_replace('"', '', $currentUsers); to remove the " from the values if you do it before the explode.
Edit2: as Ash pointed out I missed a part on the answer.
Here is the complete code:
$str = substr(str_replace('"', '', $currentUsers),1,-1);
$array = explode(",",$str);
Var_dump($array);
Echo $array[0]; // 1
Echo $array[1]; // 2
Echo $array[2]; // 4
Another solution, if the values are always numbers as in the example:
preg_match_all("/(\d+)/", $currentUsers, $array);
Simple one liner. IF it's always numbers
Working example http://www.phpliveregex.com/p/fuO
Click preg match all button first
Use eval()
$current = [];
eval('$'.$currentUsers);
var_dump($current);
For those with lightweight downvote, the output:
[root#mypc]# php test.php
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "4"
}
Related
Thanks guys.
I've been towing over this one for over a day now and it's just too difficult for me! I'm trying to remove the last 3 characters from each value within an array. Currently, I've tried converting to a string, then doing the action, then moving into a new array... can't get anything to work. Someone suggested this, but it doesn't work. I need an array of postcodes, "EC1 2AY, EC3 4XW..." converting to "EC1, EC3, ..." and it be back in an Array!!
implode(" ",array_map(function($v){ return ucwords(substr($v, 0, -3)); },
array_keys($area_elements)));
This hasn't worked, and obviously when I converted to a string and do a trim function, it will only take the last 3 characters from the last "variable" in the string.
Please send HELP!
If you want an array back, you shouldn't implode. You are almost there:
$area_elements = ['EC1 2AY', 'EC3 4XW'];
$result = array_map(function($v){
return trim(substr($v, 0, -3));
}, $area_elements);
var_dump($result);
Output:
array(2) {
[0]=>
string(3) "EC1"
[1]=>
string(3) "EC3"
}
Another solution:
altering array by reference.
Snippet
$area_elements = ['EC1 2AY', 'EC3 4XW'];
foreach($area_elements as &$v){
$v = substr($v, 0, -4);
}
print_r($area_elements);
Output
Array
(
[0] => EC1
[1] => EC3
)
Live demo
Pass by reference docs
I'm trying to remove specific element from php array with unset function. Problem is that when I var_dump array it shows all indexes (not good) but If I try to var_dump specific index PHP throws warning (good).
$a = [
'unset_me',
'leave_me',
'whatever',
];
unset($a['unset_me']);
var_dump($a);
/**
array(3) {
[0]=>
string(8) "unset_me"
[1]=>
string(8) "leave_me"
[2]=>
string(8) "whatever
*/
var_dump($a['unset_me']); // Undefined index: unset_me
Question is why php behave like this and how to remove index properly?
One more solution:
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
// remove the elements that you want
$arr = array_diff($arr, array("unset_me"));
print_r($arr);
You can try this with array_search -
unset($a[array_search('unset_me', $a)]);
If needed then add the checks like -
if(array_search('unset_me', $a) !== false) {
unset($a[array_search('unset_me', $a)]);
}
Demo
$arr = array('unset_me','leave_me','whatever',);
print_r($arr);
echo '<br/>';
$key = array_search('unset_me', $arr);
if($key !== false)
unset($arr[$key]);
print_r($arr);
I recently encountered this problem and found this solution helped:
unset($a[array_flip($a)['unset_me']]);
Just to explain what is going on here:
array_flip($a) switches the items for the key. So it would become:
$a = [
'unset_me' => 0,
'leave_me' => 1,
'whatever' => 2,
];
array_flip($a)['unset_me'] therefore resolves to being 0. So that expression is put into the original $a which can then be unset.
2 caveats here:
This would only work for your basic array, if you had an array of objects or arrays, then you would need to choose one of the other solutions
The key that you remove will be missing from the array, so in this case, there will not be an item at 0 and the array would start from 1. If it is important to you, you can do array_values($a) to reset the keys.
I have this variable $csv = '3,6,7,8'; that i need to convert to a square bracketed array of the form $csv_array = [3,6,7,8];
If i explode the csv like $new_array=explode(",",$csv);,it does not give me the array i want.
This is a running example http://3v4l.org/kYC0g
The code
$csv = '3,6,7,8';
$new_csv = '['.$csv.']';
if(is_array($new_csv)){
echo 'true';
}
else{
echo 'false';
//this is false
}
echo '<br/>';
$new_array=explode(",",$csv);
print_r($new_array);
//not what i am looking for
echo '<br/>';
print_r($new_csv);
echo '<br/>';
echo $new_csv;
As stated by a fellow stacker
RichardBernards - The two 'types' of array are exactly the same in PHP. If you are looking for JSON
An example of using JSON to achieve what it is you require:
To encode:
$csv = '3,6,7,8';
$array = explode(",", $csv);
$json = json_encode($array);
echo $json;
To decode $csv into the normal array you provided it:
$decoded = json_decode($json, true);
var_dump($decoded);
And then to return it to its original format:
$csv = implode(',', $decoded);
See json_encode() for more information, and also see it's opposite json_decode()
Keep in mind that JSON is literally a string and is not compatible associatively in PHP until it is decoded using the json_decode() function mentioned above. With that being said, replacing true with false in the example above would create an object array and multi-dimensional arrays would require them to be referenced differently, e.g. $array->result.
It would also be worth bringing to your attention the beauty of the predefined CSV functions within PHP
Adding [ and ] to string does not makes it PHP array.
$csv = '3,6,7,8';
var_dump(explode(',', $csv));
array(4) {
[0]=>
string(1) "3"
[1]=>
string(1) "6"
[2]=>
string(1) "7"
[3]=>
string(1) "8"
}
That is equal to ["3", "6", "7", "8"] as PHP array.
To get JSON array form it, use json_encode(explode(',', $csv)). Or simply $jsonArray = "[{$csv}]" if you need JSON array (not PHP array, because it will be simple string).
I want to sort elements of an array which have string values (word) according to word length.
I am performing insertion sort:
$str="welcome to php";
$st=explode(" ",$str);
$a=count($st);
for($i=0;$i<$a;$i++)
{
for($j=0;$j<$a;$j++)
{
if(strlen($st[$j])<strlen($st[$j+1]))
{$t=$st[$j];
$st[$j]=$st[$j+1];
$st[$j+1]=$t;}
}}
So the problem is $st[$j+1]. It doesn't get next value of array. It gives undefined offset. How can I get next value of array?
Somthing like this should work for you:
<?php
function lengthSort($a, $b){
return strlen($b) - strlen($a);
}
$str = "welcome to php";
$st = explode(" ", $str);
usort($st,'lengthSort');
var_dump($st);
?>
Output:
array(3) {
[0]=>
string(7) "welcome"
[1]=>
string(3) "php"
[2]=>
string(2) "to"
}
Also as Nick J suggested take a look at the foreach loop! It's very powerful!
You can define your own comparison function using php's usort function.
See http://php.net/manual/en/function.usort.php
So all you have to do is write your own function that compares strings by their length, then call usort and pass in your function.
This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
Suppose I have an array like this
$array = ['a','b','c','d']
Now in order to see it on screen, i have two options:
var_dump or print_r
But their output is like
Array ( [0] => a [1] => b [2] => c [3] => d )
or
array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string(1) "d" }
I sometimes find it difficult to read.
Is there any way to get the output like
['a','b','c','d']
so that it's easy to read?
Seems like you are needing it for reading purposes.. for that make use of json_encode();
<?php
$array = ['a','b','c','d'];
echo json_encode($array); //"prints" ["a","b","c","d"]
You can make your own function:
function print_array($array) {
echo '[';
foreach($array as $letter) {
echo $letter . ',';
}
echo ']';
}
$arr = ['a','b','c','d'];
print_array($arr);
you should add
<pre></pre>
tag before and after print_r function and suparet them
I use
echo "<pre>".print_r($array,1)."</pre>";
The output of var_dump or print_r is readable - the problem is the html output, which removes line-breaks.
So I suggest to use this functions inside a pre-tag
echo '<pre><code>';
var_dump($data);
echo '</code></pre>';
Also you could install the php module xdebug which could modify the output of var_dump for better readability: http://xdebug.org/docs/display