PHP string and number to an array - php

I have php var with multiple string values and numbers,
$string = 'Simple 12, Complex 16';
i explode this to an array, but i need to explode this string to be like below array.
Array(
[0] => Array(
[Simple] => 12,
[Complex] => 16
)
)
what is the perfect way to do this in php?

Here's a quick way:
preg_match_all('/(\w+)\s*(\d+)/', $str, $matches);
$result = array_combine($matches[1], $matches[2]);

<?php
$string = 'Simple 12, Complex 16';
$values=explode(",",$string);
$result=array();
foreach($values as $value)
{
$value=trim($value);
list($type,$count)=explode(" ",$value);
$result[0][$type]=$count;
}
print_r($result);
?>
Output
Array
(
[0] => Array
(
[Simple] => 12
[Complex] => 16
)
)
Demo

Do like this, if you want to get out put like this.
<?PHP
$string = 'Simple 12, Complex 16';
$my_arr1 = explode(',',$string);
foreach ($my_arr1 as $value) {
$value=trim($value);
$my_arr2 = explode(' ',$value);
$final_array[$my_arr2[0]]=$my_arr2[1];
}
print_r($final_array);
OUTPUT
Array
(
[Simple] => 12
[Complex] => 16
)

<?php
preg_match_all("/[A-Za-z]+/","Simple 12, Complex 16",$keys);
preg_match_all("/[0-9]{2}/","Simple 12, Complex 16",$vals);
$a = array_combine($keys[0],$vals[0]);
print_r($a);
try it out

The reply from user "Ø Hanky Panky Ø", have an error:
Here:
$result[0][$type]=$count;
Correctly is:
$result[][$type]=$count;

preg_match_all('/(\w+)\s*(\d+)/', $string, $matc);
$output = array_combine($match[1], $match[2]);

Related

PHP String(which contain array of object) to Array conversion

Suppose I have a string (which contain array of objects):
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
My goals is to get the output to look like this when I print_r:
Array
(
[0] => Array
(
[test] => 1
[anothertest] => 2
)
[1] => Array
(
[test] => 3
[anothertest] => 4
)
)
I tried to json_decode($string) but it returned NULL
Also tried my own workaround which is kinda solved the problem,
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = substr($string, 1, -1);
$string = str_replace("'","\"", $string);
$string = str_replace("},","}VerySpecialSeparator", $string);
$arrayOfString = explode("VerySpecialSeparator",$string);
$results = [];
foreach($arrayOfString as $string) {
$results[] = json_decode($string, true);
}
echo "<pre>";
print_r($results);
die;
But is there any other ways to solve this?
As per your given data, if quotes will be corrected, then you will get your desired output, so get it done like below:
<?php
$string = "[{'test':'1', 'anothertest':'2'}, {'test':'3', 'anothertest':'4'}]";
$string = str_replace("'",'"', $string);
print_r(json_decode($string,true));
https://3v4l.org/PDI7O

how to remove part of values from array in php

I have an array with date & time like below:
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
From each value, the T10:00 should be cut off, so that my new array looks like this:
$new_array = array('2021-05-04', '2021-05-05', '2021-05-06');
How can i do that?
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
$new_array = [];
foreach($array as $a) {
$a = explode('T', $a)[0];
array_push($new_array, $a);
}
Iterate through the array by array_map with callback function take only first 10 chars, Which represent time.
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
$new_array = array_map(fn($time)=>substr($time, 0, 10), $array);
print_r($new_array);
Prints:
/*
Array
(
[0] => 2021-05-04
[1] => 2021-05-05
[2] => 2021-05-06
)
*/
the T10:00 should be cut off
If you have a constant time T10:00 and want to get rid of it just replace it with empty!
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
$new_array = array_map(fn($time)=>str_replace('T10:00', '', $time), $array);
print_r($new_array);
//Array ( [0] => 2021-05-04 [1] => 2021-05-05 [2] => 2021-05-06 )

Compare a string and a php array and only show the matches

I have a string that looks like this:
"illustration,drawing,printing"
I have an array that looks like this:
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
How can I compare the two and only display the terms that exist in both the string and array?
So in the above example, I would want to output something that looks like this:
SKILLS: illustration, drawing
Thank you!
use explode(), array_intersect() and implode()
<?php
$string = "illustration,drawing,printing";
$array = Array (
0 => 'illustration',
1 => 'drawing',
2 => 'painting',
3 => 'ceramics'
);
$stringArray = explode(',',$string);
$common = array_intersect($stringArray,$array);
echo "Skills :".implode(',',$common);
https://3v4l.org/StqYN
You can do something like this:
Function:
function functionName($string, $array){
$skills = '';
// Create a temp array from your string breaking appart from the commas
$temparr = explode(",", $string);
// Iterate through each of the words now
foreach($temparr as $str){
// Check to see if our current string is in the array provided
if(in_array($str, $array)){
// If it is, then add it to the string "skills"
$skills .= "${str}, ";
}
}
// Cut the last space and comma off the end of the str.
$skills = substr($skills, 0, strlen($skills) - 2);
// Return our results
return 'SKILLS: '.$skills;
}
Usage:
$string = "illustration,drawing,printing";
$array = Array (
0 => "illustration",
1 => "drawing",
2 => "painting",
3 => "ceramics"
);
// Just input our string and the array we want to search through
echo(functionName($string, $array));
Live Demos:
https://ideone.com/qyqgzo
http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42
You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:
$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);
If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"
Firstly convert that string into array.
use array_intersect();
$str = "illustration,drawing,printing";
$ar1 = explode(",",$str);
print_r ($ar1);
$ar2 = Array ("illustration","drawing","painting","ceramics");
echo "<br>";
print_r ($ar2);
$result = array_intersect($ar1, $ar2);
echo "Skills :".implode(',',$result);
OUTPUT:
Array (
[0] => illustration
[1] => drawing
[2] => printing
)
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
SKILLS: illustration, drawing

Comma-separated string to associative array with lowercase keys

I have a string like this:
$string = 'Apple, Orange, Lemone';
I want to make this string to:
$array = array('apple'=>'Apple', 'orang'=>'Orange', 'lemone'=>'Lemone');
How to achieve this?
I used the explode function like this:
$string = explode(',', $string );
But that only gives me this:
Array ( [0] => Apple [1] => Orange [2] => Lemone )
Somebody says this question is a duplicate of this SO question: Split a comma-delimited string into an array?
But that question is not addressing my problem. I have already reached the answer of that question, please read my question. I need to change that result array's key value and case. see:
Array
(
[0] => 9
[1] => admin#example.com
[2] => 8
)
to like this
Array
(
[9] => 9
[admin#example.com] => admin#example.com
[8] => 8
)
You may try :
$string = 'Apple, Orange, Lemone';
$string = str_replace(' ', '', $string);
$explode = explode(',',$string);
$res = array_combine($explode,$explode);
echo '<pre>';
print_r($res);
echo '</pre>';
Or if you need to make lower case key for resulting array use following :
echo '<pre>';
print_r(array_change_key_case($res,CASE_LOWER));
echo '</pre>';
<?php
$string = 'Apple, Orange, Lemone'; // your string having space after each value
$string =str_replace(' ', '', $string); // removing blank spaces
$array = explode(',', $string );
$final_array = array_combine($array, $array);
$final_array = array_change_key_case($final_array, CASE_LOWER); // Converting all the keys to lower case based on your requiment
echo '<pre>';
print_r($final_array);
?>
You can use array functions such as array_combine, and array_values
$string = 'Apple, Orange, Lemone';
$arr = explode(', ', $string);
$assocArr = array_change_key_case(
array_combine(array_values($arr), $arr)
);
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
print_r($array);
output will be
Array
(
[0] => Apple
[1] => Orange
[2] => Lemone
)
Now
$ar = array();
foreach ($array as $value) {
$ar[$value] = $value;
}
print_r($ar);
Your Desire Output:
Array
(
[Apple] => Apple
[Orange] => Orange
[Lemone] => Lemone
)
$valuesInArrayWithSpace = explode("," $string);
$finalArray = [];
foreach ($ValuesInArrayWitchSpace as $singleItem) {
$finalArray[trim(strtolower($singleItem))] = trim($singleItem);
}
This way you'll have what you need:
$lowerString = strtolower($string);
$values = explode(', ', $string);
$keys = explode(', ', $lowerString);
$array = array_combine($keys, $values);
print_r($array);
Or...
$csvdata = str_getcsv('Apple,Orange,Lemone');
$arr = [];
foreach($csvdata as $a) {
$arr[strtolower(trim($a))] = $a;
}
print_r($arr);
use array_flip to change the values as key and use array_combine
<?php
$string = 'Apple, Orange, Lemone';
$array = explode(', ', $string);
$new_array =array_flip($array);
$final_array = array_combine($new_array,$array)
print_r($final_array );
?>
A clean, functional-style approach can use array_reduce() after splitting on commas followed by spaces.
Before pushing the new associative values into the result array, change the key to lowercase.
Code: (Demo)
$string = 'Apple, Orange, Lemone';
var_export(
array_reduce(
explode(', ', $string),
fn($result, $v) =>
$result + [strtolower($v) => $v],
[]
)
);
Output:
array (
'apple' => 'Apple',
'orange' => 'Orange',
'lemone' => 'Lemone',
)

Explode PHP String

I need some help, is it possible to explode like this?
I have a string 45-test-sample, is it possible to have
[0]=>string == "45"
[1]=>string == "test-sample"
How can it be done?
print_r(explode('-', $string, 2)); // take some help from the limit parameter
According to the PHP manual for explode
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
Output:
Array
(
[0] => 45
[1] => test-sample
)
Explode has a limit parameter.
$array = explode('-', $text, 2);
try this
$str = "45-test-sample";
$arr = explode('-', $str, 2);
print_r($arr);
OUTPUT :
Array
(
[0] => 45
[1] => test-sample
)
Demo
Try with exact output using list.
<?php
$str = "45-test-sample";
list($a,$b) = explode('-', $str, 2);
$arr=Array();
$arr=['0'=>"String == ".$a,'1'=>"String == ".$b];
print_r($arr);
?>
Output:
Array
(
[0] => String == 45
[1] => String == test-sample
)
DEMO

Categories