How to convert Array to string in PHP without using implode method? - php

I Have an Array like this,
$arr = array_diff($cart_value_arr,$cart_remove_arr);
I Want to convert it to string without using implode method anyother way is there? And Also i want to remove $cart_remove_arr from $cart_value_arr the array_diff method i used it is correct?

You can use json_encode
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
This will also work on multi dimensional arrays
Will result to:
{"a":1,"b":2,"c":3,"d":4,"e":5}
Doc: http://php.net/manual/en/function.json-encode.php

Another way is the classic foreach plus string concatenation
$string = '';
foreach ($arr as $value) {
$string .= $value . ', ';
}
echo rtrim($string, ', ');

Yet another way is to use serialize() (http://php.net/manual/en/function.serialize.php), as simple as...
$string = serialize($arr);
This can handle most types and unserialize() to rebuild the original value.

$cart_remove_arr = array(0 => 1, 1=> 2, 2 => 3);
$cart_value_arr = array(0 => 5, 1=> 2, 2 => 3, 3 => 4, 4 => 6);
$arr = array_diff($cart_value_arr, $cart_remove_arr);
echo '<pre>';
print_r($arr);
$string = "";
foreach($arr as $value) {
$string .= $value.', ';
}
echo $string;
**Output: Naveen want to remove $cart_remove_arr from $cart_value_arr
Remaining array**
Array
(
[0] => 5
[3] => 4
[4] => 6
)
he want a similar out as implode()
**String** 5, 4, 6,

Related

PHP Array split string and Integers

Below is an array of strings and numbers. How could the string and number values be split into separate arrays (with strings in one array and numbers in another array)?
array('a','b','c',1,2,3,4,5,'t','x','w')
You could also do this in one line using array_filter()
$numbers = array_filter($arr,function($e){return is_numeric($e);});
$alphas = array_filter($arr,function($e){return !is_numeric($e);});
print_r($numbers);
print_r($alphas);
Loop through them, check if is_numeric and add to appropriate array:
$original = array('a','b','c',1,2,3,4,5,'t','x','w');
$letters = array();
$numbers = array();
foreach($original as $element){
if(is_numeric($element)){
$numbers[] = $element;
}else{
$letters[] = $element;
}
}
https://3v4l.org/CAvVp
Using a foreach() like in #jnko's answer will be most performant because it only iterates over the array one time.
However, if you are not concerned with micro-optimization and prefer to write concise or functional-style code, then I recommend using array_filter() with is_numeric() calls, then making key comparisons between the first result and the original array.
Code: (Demo)
$array = ['a','b',0,'c',1,2,'ee',3,4,5,'t','x','w'];
$numbers = array_filter($array, 'is_numeric');
var_export($numbers);
var_export(array_diff_key($array, $numbers));
Output:
array (
2 => 0,
4 => 1,
5 => 2,
7 => 3,
8 => 4,
9 => 5,
)
array (
0 => 'a',
1 => 'b',
3 => 'c',
6 => 'ee',
10 => 't',
11 => 'x',
12 => 'w',
)
$data = array('a','b','c',1,2,3,4,5,'t','x','w');
$integerArray = array();
$stringArray = array();
$undefinedArray = array();
foreach($data as $temp)
{
if(gettype($temp) == "integer")
{
array_push($integerArray,$temp);
}elseif(gettype($temp) == "string"){
array_push($stringArray,$temp);
}else{
array_push($undefinedArray,$temp);
}
}

exploding string with multiple delimiter [duplicate]

This question already has answers here:
PHP - split String in Key/Value pairs
(5 answers)
Convert backslash-delimited string into an associative array
(4 answers)
Closed 12 months ago.
i have a string like
$str = "1-a,2-b,3-c";
i want to convert it into a single array like this
$array = [
1 => "a",
2 => "b",
3 => "c"
];
what i do is
$str = "1-a,2-b,3-c";
$array = [];
$strex = explode(",", $str);
foreach ($strex as $str2) {
$alphanumeric = explode("-", $str2);
$array[$alphanumeric[0]] = $alphanumeric[1];
}
can i do this in a better way?
You can use preg_match_all for this:
<?php
$str = "1-a,2-b,3-c";
preg_match_all('/[0-9]/', $str, $keys);
preg_match_all('/[a-zA-Z]/', $str, $values);
$new = array_combine($keys[0], $values[0]);
echo '<pre>'. print_r($new, 1) .'</pre>';
here we take your string, explode() it and then preg_match_all the $value using patterns:
/[0-9]/ -> numeric value
/[a-zA-Z]/ -> letter
then use array_combine to get it into one array
Thanks to u_mulder, can shorten this further:
<?php
$str = "1-a,2-b,3-c";
preg_match_all('/(\d+)\-([a-z]+)/', $str, $matches);
$new = array_combine($matches[1], $matches[2]);
echo '<pre>'. print_r($new, 1) .'</pre>';
just a little benchmark:
5000 iterations
Debian stretch, php 7.3
parsed string: "1-a,2-b,3-c,4-d,5-e,6-f,7-g,8-h,9-i"
[edit] Updated with the last 2 proposals [/edit]
You can use preg_split with array_filter and array_combine,
function odd($var)
{
// returns whether the input integer is odd
return $var & 1;
}
function even($var)
{
// returns whether the input integer is even
return !($var & 1);
}
$str = "1-a,2-b,3-c";
$temp = preg_split("/(-|,)/", $str); // spliting with - and , as said multiple delim
$result =array_combine(array_filter($temp, "even", ARRAY_FILTER_USE_KEY),
array_filter($temp, "odd",ARRAY_FILTER_USE_KEY));
print_r($result);
array_filter — Filters elements of an array using a callback function
Note:- ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value
array_combine — Creates an array by using one array for keys and another for its values
Demo
Output:-
Array
(
[1] => a
[2] => b
[3] => c
)
One way to do with array_map(),
<?php
$my_string = '1-a,2-b,3-c';
$my_array = array_map(function($val) {list($key,$value) = explode('-', $val); return [$key=>$value];}, explode(',', $my_string));
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($my_array)) as $k=>$v){
$result[$k]=$v;
}
print_r($result);
?>
WORKING DEMO: https://3v4l.org/aYmOH
Tokens all the way down...
<?php
$str = '1-a,2-b,3-c';
$token = '-,';
if($n = strtok($str, $token))
$array[$n] = strtok($token);
while($n = strtok($token))
$array[$n] = strtok($token);
var_export($array);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
Or perhaps more terse without the first if...:
$array = [];
while($n = $array ? strtok($token) : strtok($str, $token))
$array[$n] = strtok($token);
Not a better way but one more example:
$str = "1-a,2-b,3-c";
$arr1 = explode(",", preg_replace("/\-([a-zA-Z]+)/", "", $str));
$arr2 = explode(",", preg_replace("/([0-9]+)\-/", "", $str));
print_r(array_combine($arr1, $arr2));
Mandatory one-liner (your mileage may vary):
<?php
parse_str(str_replace([',', '-'], ['&', '='], '1-a,2-b,3-c'), $output);
var_export($output);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
You can do one split on both the , and -, and then iterate through picking off every other pair ($k&1 is a check for an odd index):
<?php
$str = '1-a,2-b,3-c';
foreach(preg_split('/[,-]/', $str) as $k=>$v) {
$k&1 && $output[$last] = $v;
$last = $v;
}
var_export($output);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)
The preg_split array looks like this:
array (
0 => '1',
1 => 'a',
2 => '2',
3 => 'b',
4 => '3',
5 => 'c',
)
This one explodes the string as the OP has on the comma, forming the pairs: (1-a) and (2-b) etc. and then explodes those pairs. Finally array_column is used to create the associated array:
<?php
$str = '1-a,2-b,3-c';
$output =
array_column(
array_map(
function($str) { return explode('-', $str); },
explode(',', $str)
),
1,
0
);
var_export($output);
Output:
array (
1 => 'a',
2 => 'b',
3 => 'c',
)

How to swap two values in array with indexes?

For example i have an array like this $array = ('a' => 2, 'b' => 1, 'c' => 4); and i need to swap a with c to get this $array = ('c' => 4, 'b' => 1, 'a' => 2);. Wht is the best way for doing this without creating new array? I know that it is possible with XOR, but i also need to save indexes.
array_splice would be perfect, but unfortunately it doesn't preserve the keys in the inserted arrays. So you'll have to resort to a little more manual slicing and dicing:
function swapOffsets(array $array, $offset1, $offset2) {
list($offset1, $offset2) = array(min($offset1, $offset2), max($offset1, $offset2));
return array_merge(
array_slice($array, 0, $offset1, true),
array_slice($array, $offset2, 1, true),
array_slice($array, $offset1 + 1, $offset2 - $offset1 - 1, true),
array_slice($array, $offset1, 1, true),
array_slice($array, $offset2 + 1, null, true)
);
}
If you want to purely swap the first and the last positions, here's one way to do it:
$first = array(key($array) => current($array)); // Get the first key/value pair
array_shift($array); // Remove it from your array
end($array);
$last = array(key($array) => current($array)); // Get the last key/value pair
array_pop($array); // Remove it from the array
$array = array_merge($last, $array, $first); // Put it back together
Gives you:
Array
(
[c] => 4
[b] => 1
[a] => 2
)
Working example: http://3v4l.org/r87qD
Update: And just for fun, you can squeeze that down quite a bit:
$first = array(key($array) => current($array));
$last = array_flip(array(end($array) => key($array)));
$array = array_merge($last, array_slice($array,1,count($array) - 2), $first);
Working example: http://3v4l.org/v6R7T
Update 2:
Oh heck yeah, we can totally do this in one line of code now:
$array = array_merge(array_flip(array(end($array) => key($array))), array_slice($array,1,count($array) - 2), array_flip(array(reset($array) => key($array))));
Working example: http://3v4l.org/QJB5T
That was fun, thanks for the challenge. =)

Select 2 random elements from associative array

So I have an associative array and I want to return 2 random values from it.
This code only returns 1 array value, which is any of the 4 numbers at random.
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$key = array_rand($array); //array_rand($array,2); Putting 2 returns Illegal offset type
$value = $array[$key];
print_r($value); //prints a single random value (ex. 3)
How can I return 2 comma separated values from the array values only? Something like 3,4?
array_rand takes an additional optional parameter which specifies how many random entries you want out of the array.
$input_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$rand_keys = array_rand($input_array, 2);
echo $input_array[$rand_keys[0]] . ',' . $input_array[$rand_keys[1]];
Check the PHP documentation for array_rand here.
Grab the keys from the array with array_keys(), shuffle the keys with shuffle(), and print out the values corresponding to the first two keys in the shuffled keys array, like so:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_keys( $array);
shuffle( $keys);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];
Demo
Or, you can use array_rand()'s second parameter to grab two keys, like so:
$array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$keys = array_rand( $array, 2);
echo $array[ $keys[0] ] . ',' . $array[ $keys[1] ];
Demo
There is a more efficient approach that preserves keys and values.
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
Check the documentation here
$a=rand(0,sizeof($array));
$b=$a;
while ($a==$b) $b=rand(0,sizeof($array));
$ar=array_values($array);
$element1=$ar[$a];
$element2=$ar[$b];
Should be more efficient than shuffle() and freinds, if the array is large.

where to use array() in PHP

can you give me examples of using array() function ?
There are plenty of examples in the manual:
http://php.net/manual/en/language.types.array.php
more specifically:
http://www.php.net/manual/en/function.array.php
$somearray = array();
$somearray[] = 'foo';
$somearray[] = 'bar';
$someotherarray = array(1 => 'foo', 2 => 'bar');
var_dump($somearray);
echo $someotherarray[2];
$a = array(1, 'test'=>2,'testing'=>'yes');
foreach($a as $key => $value) {
echo $key . ' = ' . $value . '<br />';
}
Even easier to see the output...
print_r($a);
$arr = array(1, 2, 3, 4, 5);
To loop over each element in the array:
foreach($arr as $val) {
print "$var\n";
}
One interesting thing to note about PHP arrays is that they are all implemented as associative arrays. You can specify the key if you want, but if you don't, an integer key is used, starting at 0.
$array = array(1, 2, 3, 4, 5);
is the same as (with keys specified):
$array = array(0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5);
is the same as:
$array = array('0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5);
Though, if you want to start the keys at one instead of zero, that's easy enough:
$array = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5);
Though if you don't specify the key value, it takes the highest key and adds one, so this is a shortcut:
$array = array(1 => 1, 2, 3, 4, 5);
The key (left side) can only be an integer or string, but the value (right side) can be any type, including another array or an object.
Strings for keys:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
Two easy ways to iterate through an array are:
$array = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5);
foreach($array as $value) {
echo "$value\n";
}
foreach($array as $key => $value) {
echo "$key=$value\n";
}
To test to see if a key exists, use isset():
if (isset($array['one'])) {
echo "$array['one']\n";
}
To delete a value from the array, use unset():
unset($array['one']);

Categories