Convert string into an array with certain format - php

How can you convert a string that contains your first and last name and sometimes middle name into an array with this format?
customFunction('Chris Morris');
// array('firstname' => 'Chris', 'lastname' => 'Morris')
customFunction('Chris D. Morris');
// array('firstname' => 'Chris D.', 'lastname' => 'Morris')
customFunction('Chris');
// array('firstname' => 'Chris', 'lastname' => '')

Try this
function splitName($name){
$name = explode(" ",$name);
$lastname= count($name)>1 ? array_pop($name):"";
return array("firstname"=>implode(" ",$name), "lastname"=>$lastname);
}

you can try this:
<?php
$arr = 'Chris D. Morris';
function customFunction($str){
$str = trim($str);
$lastSpace = strrpos($str," ");
if($lastSpace == 0){
$first = $str;
return array('firstname' => $first, 'lastname' => $last);
}else{
$first = substr($str, 0, $lastSpace);
$last = substr($str,$lastSpace);
return array('firstname' => $first, 'lastname' => $last);
}
}
$got = customFunction($arr);
print_r($got);
?>
hope it helps.

function parseName($input) {
$retval = array();
$retval['firstname'] = '';
$retval['lastname'] = '';
$words = explode(' ', $input);
if (count($words) == 1) {
$retval['firstname'] = $words[0];
} elseif (count($words) > 1) {
$retval['lastname'] = array_pop($words);
$retval['firstname'] = implode(' ', $words);
}
return $retval;
}

Related

Array to comma separated string?

My php code is
public function getAllAttributes()
{
$this->dao->select('b_title');
$this->dao->from($this->getTable_buttonsAttr());
$result = $this->dao->get();
if( !$result ) {
return array() ;
}
return $result->result();
}
$details = Modelbuttons::newInstance()->getAllAttributes();
$string = implode(', ', $details);
var_dump ($string) ; ?>
I get this an array that looks like this:
array (size=6)
0 =>
array (size=1)
'b_title' => string 'test 10' (length=12)
1 =>
array (size=1)
'b_title' => string 'test 11' (length=12)
2 =>
array (size=1)
'b_title' => string 'test 12' (length=13)
3 =>
array (size=1)
'b_title' => string 'test 13' (length=8)
4 =>
array (size=1)
'b_title' => string 'test 14' (length=14)
5 =>
array (size=1)
'b_title' => string 'test 15' (length=32)
How can I transform this array to a string like this with PHP?
$out = '10, 11, 12, 13, 14,15';
You can try this code.
$array = [['b_title' => 'test 10'],['b_title' => 'test 11']];
foreach($array as $a) {
$values[] = explode(' ', $a['b_title'])[1];
}
echo implode(', ', $values);
Basic Example:
<?php
// your array
$array = array(
array('b_title'=>'test 10'),
array('b_title'=>'test 11'),
array('b_title'=>'test 12'),
array('b_title'=>'test 13')
);
$newArr = array();
foreach ($array as $key => $value) {
$newVal = explode(" ", $value['b_title']);
$newArr[] = $newVal[1];
}
echo implode(',', $newArr); // 10,11,12,13
?>
Explanation:
First of all use explode() for your string value which help you to Split a string as required:
$newVal = explode(" ", $value['b_title']);
Than you can store index 1 in an array as:
$newArr[] = $newVal[1]; // array(10,11,12,13)
In last, you just need to use implode() function which help you to get comma separated data.
echo implode(',', $newArr); // 10,11,12,13
An alternative way to do.
$details = Modelbuttons::newInstance()->getAllAttributes(); /*[['b_title' => 'test 10'],['b_title' => 'test 11']];*/
$token = "";
foreach($details as $row1){
$token = $token.$row1['b_title'].", ";
}
echo rtrim(trim($token),",");
Output: test 10, test 11
Explanation
Through foreach, all array values are now comma separated.
As of now, output will be test 10, test 11,. So, remove extra comma which trail in the end through rtrim().
There are many ways to skin this cat -- Here's one:
<?php
$out = '';
foreach ($array as $arrayItem) {
$out .= $arrayItem['b_title'] . ', ';
}
// Remove the extraneous ", " from the $out string.
$out = substr($out, 0, -2);
?>
Or if you were also wanting to remove the "test " portion of the 'b_title' key's value; then you could accomplish it like so:
<?php
$out = '';
foreach ($array as $arrayItem) {
$out .= str_replace('test ', '', $arrayItem['b_title']) . ', ';
}
// Remove the extraneous ", " from the $out string.
$out = substr($out, 0, -2);
?>
// Construct a new array of the stripped numbers
$flattenedArray = array_map(function($item) {
list(, $number) = explode(' ', $item['b_title']);
return $number;
}, $yourArray);
// Concatenate the numbers into a string joined by ,
$out = implode(', ', $flattenedArray);
This gives the result you want. It could do with a few conditions in there though to check arrays are in the correct format before manipulation etc.
You can try this also
$check = array(array ('b_title' => array('test 10'))
,array('b_title' => array('test 11'))
,array('b_title' => array('test 12'))
,array('b_title' => array('test 13'))
,array('b_title' => array('test 14'))
,array('b_title' => array('test 15')));
$srt = "";
foreach($check as $kye => $val)
{
$title = $val['b_title'][0];
$var = explode(' ',$title);
$srt .= trim($var[1]).', ';
}
$srt = substr(trim($srt),0,-1);
$test_array = array(
0 => array('b_title' => 'test 10'),
1 => array('b_title' => 'test 11'),
2 => array('b_title' => 'test 12'),
3 => array('b_title' => 'test 13'),
4 => array('b_title' => 'test 14'),
5 => array('b_title' => 'test 15'),
);
$result = "";
$result1 = array_walk($test_array, function ($value, $key) use(&$result) {
$result .= ",".array_pop(explode(" ", reset($value))).",";
$result = trim($result, ",");
});
Output: $out = '10, 11, 12, 13, 14,15';
Explanation
Iterate over array by using PHP's native array_walk() which will reduce forloops and then prepare array by using explode(),array_pop() and trim() which is likely required to prepare your required string.
Try this,
foreach($test_array as $val)
{
$new_array[] = preg_replace('/\D/', '', $val['b_title']);
}
$out = implode(',', $new_array);
echo $out;
OUTPUT
10,11,12,13,14,15
DEMO
You can use on mentioned URL solution Click here
foreach ($arr as $k=>$val) {
$v = explode (' ', $val['b_title']);
$out .= $v[1].',';
}
$out = rtrim ($out, ',');
echo '<pre>'; print_r($out); die;

return array from function php

I need this function to return an array. When I call the function it is printing the array, but when I use return $finalResult in the function, it is only printing the first array.
function readData($file)
{
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach ($textLines as $line)
{
$expLine = explode("\t", $line);
if (count($expLine) < 8)
{
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" => $expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr = $finalResult;
print_r($arr);
}
}
Hi You mush merge or push array to $finalResult see sammple
function readData($file){
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
//Here []
$finalResult[] = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
//$arr=$finalResult;
//print_r($arr);
}
return $finalResult;
}
As described in my comment above
function readData($file){
$arr = array();
$finalResult = array();
$inputText = file_get_contents($file);
$textLines = explode("\n", $inputText);
foreach($textLines as $line) {
$expLine = explode("\t", $line);
if (count($expLine) < 8) {
# The line does not have enough items, deal with error
//echo "Item " . (isset($expLine[0]) ? $expLine[0]." " : "") . "ignored because of errors\n";
continue;
}
$finalResult = array(
"title" =>$expLine[0],
"author" => $expLine[1],
"isbn" => $expLine[2],
"hardcover" => $expLine[3],
"hc-quantity" => $expLine[4],
"softcover" => $expLine[5],
"sc-quantity" => $expLine[6],
"e-book" => $expLine[7],
);
$arr=array_merge($arr, $finalResult);
}
return $arr;
}

upload image files can not be displayed

why images can not be performed when added
if(isset($_POST['tambah'])){
$data1 = array(
'id' => $_POST['id'],
'nama' => $_POST['nama'],
'jk' => $_POST['jk'],
'tempat' => $_POST['tempat'],
'tanggal' => date('Y-m-d',strtotime("$_POST[tanggal]")),
'pekerjaan' => $_POST['pekerjaan'],
'alamat' => $_POST['alamat'],
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '..asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
);
use function :
function tambahAnggota($data1){
$kunci = implode(", ",array_keys($data1));
$i = 0;
foreach ($data1 as $key => $value) {
if (!is_int($value)){
$arrayValue[$i] = "'".$value."'";
}else{
$arrayValue[$i] = $value;
}
$i++;
}
$nilai = implode(", ", $arrayValue);
print_r($nilai);
die();
$s = "insert into anggota ($kunci)";
$s .= " VALUES ";
$s .= "($nilai)";
$sql = $this->db->prepare($s); /*or die ($this->db->connect_errno);*/
$sql->execute();
}
will be added all the data except the image data file to be uploaded
will look like this :
'DA123', 'David', 'laki', 'Los Angeles', '1987-03-12', 'Web Developer', 'foof st.', ''
You have an error in your path : you write '..asset/img/anggota/' which is not correct.
Try with ../asset/img/anggota/ (notice the / after ..).
Just replace :
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '..asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))
With :
'foto' => move_uploaded_file($FILES['photo']['temp_name'], '../asset/img/anggota/'.str_replace(' ', '-', $_POST['id'].'.jpg'))

Imploding with "and" in the end?

I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>

How to Split/explode a string by lasr occurance of dot in php?

Hii Friends,
I have strings in php like
abc.com
abc.name.com
abc.xyz.name.org
Now i want to split above domain name(Bold text) as
string1=abc string2=com
string1=abc string2=name.com
string1=abc.xyz string2=name.org
Means i want to split user name and domain name.
So please help me.
You can try with:
$inputs = ['abc.com', 'abc.name.com', 'abc.xyz.name.org'];
foreach ($inputs as $input) {
$parts = explode('.', $input);
$right = [array_pop($parts)];
if (count($parts) > 1) {
$right[] = array_pop($parts);
}
$output = [
'left' => implode('.', $parts),
'right' => implode('.', $right),
];
var_dump($output);
}
Outputs:
array (size=2)
'left' => string 'abc' (length=3)
'right' => string 'com' (length=3)
array (size=2)
'left' => string 'abc' (length=3)
'right' => string 'com.name' (length=8)
array (size=2)
'left' => string 'abc.xyz' (length=7)
'right' => string 'org.name' (length=8)
Use array_pop() function after explode():
$vars = explode('.', $string);
if ( count($vars) == 3 ) {
$string2 = $vars[1] . '.' . $vars[2];
$string1 = $vars[0];
}
if ( count($vars) == 2 ) {
$string2 = $vars[1];
$string1 = $vars[0];
}
// Or you may use
$vars = explode('.', $string);
if ( count($vars) == 3 ) {
$string2 = $vars[1] . '.' . $vars[2];
$string1 = $vars[0];
}
if ( count($vars) == 2 ) {
$string2 = array_pop($vars);
$string1 = array_pop($vars);
}
Check pop and explode in php.net
http://php.net/manual/en/function.array-pop.php
http://php.net/manual/en/function.explode.php
This should do the trick. I tried to make it as verbose as possible. Online test
<?php
function get_last_dot_occurence ($url ) {
$fullArray = explode('.', $url);
$newArray = "";
switch (count($fullArray)) {
case 0:
break;
case 1:
$newArray = $url;
break;
case 2:
$newArray = array("string1" => $fullArray[0], "string2" => $fullArray[1]);
break;
default:
$string1 = "";
for ($i=0; $i < count($fullArray)-2; $i++) {
$string1 .= $fullArray[$i];
if($i != count($fullArray)-3)
$string1 .= '.';
}
$string2 = $fullArray[count($fullArray)-2].'.'.$fullArray[count($fullArray)-1];
$newArray = array("string1" => $string1, "string2" => $string2);
break;
}
return $newArray;
}
print_r(get_last_dot_occurence("abc.com"));
print_r(get_last_dot_occurence("abc.name.com"));
print_r(get_last_dot_occurence("abc.xyz.name.org"));

Categories