How to split array in php with 2 strings? - php

How to split array with , in 2 parts so that that can be used as 2 strings in php?
I am getting this kind of array you can view image with this list.
I want to split this array to post id and title in separate columns.
<li id="recordsArray_'.$value['id'].','.$value['title'].'"></li>

Give a try with below code if it works for you
$arr = array('1,test1','2,test2','3,test3');
foreach($arr as $ar){
$res = explode(',', $ar);
$id = $res[0];
$title = $res[1];
echo 'id-'.$id;
echo ' title-'.$title;
echo '<br>';
}

If you want to separate array into two string, you can use explode like this short code:
$item = '4,test';
$var = explode(',', $item);
echo $var;
and for loop array, you can use
$array = array(YOUR_ARRAY);
foreach($array as $item){
$var = explode(',', $item);
echo $var;
}
Update 1:
You can use a simple array like below code:
$array = array(4, 'salar');
and use a code like this:
$array = array(4, 'salar');
foreach ($array as $item) {
dump(explode(',', $item));
}

Related

Pass comma separated key string and get value of array according to key in PHP

I am trying to get value from array and pass only comma separated key string and get same output without. Is it possible without using foreach statement. Please suggest me.
<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
$valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);
?>
Output : apple,banana,orange
Use array_intersect_key
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
echo implode(",", array_intersect_key($array, array_flip($keyarray)));
https://3v4l.org/gmcON
One liner:
echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));
A mess to read but a comment above can explain what it does.
It means you don't need the $keyarray
Suggestion : Use separate row for each value, to better operation. Although you have created right code to get from Comma sparate key to Value from array, but If you need it without any loop, PHP has some inbuilt functions like array_insersect , array_flip to same output
$str = "1,2";
$arr1 = ["1"=>"test1","2"=>"test2","3"=>"test3"];
$arr2 = explode(",",$str);
echo implode(", ",array_flip(array_intersect(array_flip($arr1),$arr2)));
Live demo
you can try using array_filter:
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");
$keyarray = explode(",",$str);
$filtered = array_filter($array, function($v,$k) use($keyarray){
return in_array($k, $keyarray);
},ARRAY_FILTER_USE_BOTH);
print_r($filtered);
OUTPUT
Array
(
[1] => apple
[2] => banana
[3] => orange
)
Another way could be using array_map():
echo $valStr = implode(",", array_map(function ($i) use ($array) { return $array[$i]; }, explode(",", $str)));
Read it from bottom to top:
echo $valStr = implode( // 3. glue values
",",
array_map( // 2. replace integers by fruits
function ($i) use ($array) {
return $array[$i];
},
explode(",", $str) // 1. Split values
)
);

array_combine wont work with duplicate value

I have two string :
$var1 = "1,2";
$var2 = "5,5";
I want output like:
5:1 5:2
I have tried explode() with array_combine() but it gives output like 5:2
My php code:
$res = array_combine(explode(',', $var2), explode(',', $var1));
foreach($res as $key=>$val) {
echo "$key:$val ";
}
Array keys must be unique and with your code you have two number 5, so you will get the second one. You could loop one array and access the other with the same key:
$array1 = explode(',', $var1);
$array2 = explode(',', $var2);
foreach($array2 as $key => $val) {
echo "$val:{$array1[$key]} ";
}

What is the best way to go through one column in a multi dimentional array

Suppose I have the array $array where:
$array[0] = {'a','b','c'}
$array[1] = {'d','e','f'}
And I want to iterate over the first column of the nested array in order to get 'a','d' only. What is the most efficient way to do that other than having a loop that iterates on $array[n][0]?
For PHP < 5.3 you can use array_map function like as
$array[0] = ['a','b','c'];
$array[1] = ['d','e','f'];
echo implode(',',array_map(function($v){ return $v[0];},$array));//a,d
As #Rizier123 commented you can simply use array_shift as callback function like as
echo implode(',',array_map('array_shift',$array));//a,d
Demo
Try this -
$array[0] = ['a','b','c'];
$array[1] = ['d','e','f'];
$new = array_column($array, 0);
foreach($new as $v) {
echo $v . ' ';
}
Output
a d
For lower versions of PHP -
$new = array();
foreach($array as $a) {
$new[] = $a[0];
}

Replace string with values from multidimensional array based on a key

I have a variable with multiple number stored as a string:
$string = "1, 2, 3, 5";
and multidimensional array with other stored values:
$ar[1] = array('title#1', 'filename#1');
$ar[2] = array('title#2', 'filename#2');
$ar[3] = array('title#3', 'filename#3');
$ar[4] = array('title#4', 'filename#4');
$ar[5] = array('title#5', 'filename#5');
My goal is to replace number from $string with related tiles from $ar array based on associated array key. For an example above I should to get:
$string = "title#1, title#2, title#3, title#5";
I have tried to loop through $ar and do str_replace on $string, but final value of $string is always latest title from related array.
foreach($ar as $key => $arr){
$newString = str_replace($string,$key,$arr[0]);
}
Any tips how to get this solved?
Thanks
you can do it by str_replace by concat each time or you can do it by explode and concat.
Try Like this:
$string = "1, 2, 3, 5";
$arrFromString = explode(',', $string);
$newString = '';
foreach($ar as $intKey => $arr){
foreach($arrFromString as $intNumber){
if($intKey == $intNumber) {
$newString .= $arr[0].',';
}
}
}
$newString = rtrim($newString,',');
echo $newString;
Output:
title#1,title#2,title#3,title#5
live demo
You can use explode() and implode() functions to get the numbers in $string as an array and to combine the titles into a string respectively:
$res = array();
foreach (explode(", ", $string) as $index) {
array_push($res, $ar[$index][0]);
}
$string = implode(", ", $res);
print_r($string);
will give you
title#1, title#2, title#3, title#5;

How to add a word before or after some string lines

Using PHP, i have a list of names , I want to add this at the first of each lines:
'http://
And add this one to the last of each line :
' ,
Example >>
I have this :
john
michel
hosein
ali
And i want this :
'http://john' ,
'http://michel ' ,
'http://hosein' ,
'http://ali' ,
Is there any code to do this for me ?
if your lines are in an array, you could use something like this:
$out = array_map(function($item) {
return "'http://{$item}', ";
}, $data);
if they aren't you have to use explode(or an preg_split) to put them into an array
I hope this code will help:
<?
$lineStart= "'http://";
$lineEnd = "' , ";
$names = array("john", "michel", "hosein", "ali"); //array with names
for ($i=0; $i<count($names) ; $i++) //echo as many times as the number of names in a string
{
echo $lineStart.$names[$i].$lineEnd."<br>"; //just string concatenation
}
?>
For example your values are in an array named $array and you want to save the new format in an array named $new_array you can try like this:
$new_array = array();
foreach($array as $value) {
$new_array[] = "'http://".$value."' ,";
}
<?php
$ary = array("john", "michel", "hosein", "ali");
$newArray = array();
foreach($ary as $val)
$newArray[] = "'http://" .$val. "', ";
?>
To get the names list from the file,
EDIT :
<?php
$ary = file("inputfile.txt", FILE_IGNORE_NEW_LINES);
$newArray = array();
foreach($ary as $val) {
$newArray[] = "'http://".$val."', ";
}
?>
Here, the inputfile.txt contains the names line by line.
ex.
john
michel
hosein
ali

Categories