create array with key and value from string - php

I have a string:
$content = "test,something,other,things,data,example";
I want to create an array where the first item is the key and the second one the value.
It should look like this:
Array
(
[test] => something
[other] => things
[data] => example
)
How can I do that? It's difficult to search for a solution because I don't know how to search this.
It's very similar to this: Explode string into array with key and value
But I don't have a json array.
I tried something like that:
$content = "test,something,other,things,data,example";
$arr = explode(',', $content);
$counter = 1;
$result = array();
foreach($arr as $item) {
if($counter % 2 == 0) {
$result[$temp] = $item;
unset($temp);
$counter++;
} else {
$temp = $item;
$counter++;
continue;
}
}
print_r($result);
But it's a dirty solution. Is there any better way?

Try this:
$array = explode(',',$content);
$size = count($array);
for($i=0; $i<$size; $i++)
$result[$array[$i]] = $array[++$i];

Try this:
$content = "test,something,other,things,data,example";
$data = explode(",", $content);// Split the string into an array
$result = Array();
$size = count($data); // Calculate the size once for later use
if($size%2 == 0)// check if we have even number of items(we have pairs)
for($i = 0; $i<$size;$i=$i+2){// Use calculated size here, because value is evaluated on every iteration
$result[$data[$i]] = $data[$i+1];
}
var_dump($result);

Try this
$content = "test,something,other,things,data,example";
$firstArray = explode(',',$content);
print_r($firstArray);
$final = array();
for($i=0; $i<count($firstArray); $i++)
{
if($i % 2 == 0)
{
$final[$firstArray[$i]] = $firstArray[$i+1];
}
}
print_r($final);

$content = "test,something,other,things,data,example";
$x = explode(',', $content);
$z = array();
for ($i=0 ; $i<count($x); $i+=2){
$res[$x[$i]] = $x[$i+1];
$z=array_merge($z,$res);
}
print_r($z);

I have tried this example this is working file.
Code:-
<?php
$string = "test,something|other,things|data,example";
$finalArray = array();
$asArr = explode( '|', $string );
foreach( $asArr as $val ){
$tmp = explode( ',', $val );
$finalArray[ $tmp[0] ] = $tmp[1];
}
echo "After Sorting".'<pre>';
print_r( $finalArray );
echo '</pre>';
?>
Output:-
Array
(
[test] => something
[other] => things
[data] => example
)
For your reference check this Click Here
Hope this helps.

You could able to use the following:
$key_pair = array();
$arr = explode(',', $content);
$arr_length = count($arr);
if($arr_length%2 == 0)
{
for($i = 0; $i < $arr_length; $i = $i+2)
{
$key_pair[$arr[$i]] = $arr[$i+1];
}
}
print_r($key_pair);

$content = "test,something,other,things,data,example";
$contentArray = explode(',',$content);
for($i=0; $i<count($contentArray); $i++){
$contentResult[$contentArray[$i]] = $contentArray[++$i];
}
print_r( $contentResult);
Output
Array
(
[test] => something
[other] => things
[data] => example
)
$contentResult[$contentArray[1]] = $contentArray[2];
$contentResult[$contentArray[3]] = $contentArray[4];
$contentResult[$contentArray[5]] = $contentArray[6];

Related

How to add string into array in PHP?

I have these for loop to determine consecutive number. What I achieve so far is to print the output in string.
$arr = [1,2,3,6,11,5,4,8,9,3];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
echo 'Number is '.$arr[$start].','.$arr[$end].'<br/>';
} else {
echo '';
}
$arr[$start++];
}
}
My goal is to add the output into array.
I tried to use multidimensional array but no output display.
$arr = [1,2,3,6,11,5,4,8,9,3];
$arr3 = [];
for($start=0; $start<=count($arr); $start++){
for($end=$start+1; $end<=count($arr); $end++){
$total = $arr[$end] - $arr[$start];
if($total == 1){
$arr2 = array();
$arr2[] = $arr[$start].','.$arr[$end].'';
$arr3[] = $arr2;
} else {
}
$arr[$start++];
}
}
echo '<pre>';
print_r($arr3);
echo '</pre>';
exit;
Appreciate if someone can help me. Thanks.
you can simply use array functions, if sorting is important to you as #nice_dev said, you must sort your array before.
$arr = [1,2,3,6,11,5,4,8,9,3];
$cons = [] ;
while (array_key_last($arr) != key($arr)) {
if ((current($arr)+1) == next($arr)) {
prev($arr);
$cons[] = current($arr) . ',' . next($arr);
}
}
print_r($cons);
the output will be :
Array
(
[0] => 1,2
[1] => 2,3
[2] => 8,9
)
You can better sort() the input array first. This way, collecting all consecutive elements would get much simpler. If value at any index isn't +1 of the previous one, we add the $temp in our $results array and start a new $temp from this index.
Snippet:
<?php
$arr = [1,2,3,6,11,5,4,8,9,3];
$result = [];
sort($arr);
$temp = [];
for($i = 0; $i < count($arr); ++$i){
if($i > 0 && $arr[ $i ] !== $arr[$i - 1] + 1){
$result[] = implode(",", $temp);
$temp = [];
}
$temp[] = $arr[$i];
if($i === count($arr) - 1) $result[] = implode(",", $temp);
}
print_r($result);
Online Demo

unable to find error with array_merge

I am trying to insert batch query in code igniter, I am not able to make array_merge work. Don't know whats the problem. M getting blank array.
$epin_amt = $this->input->post('amount');
$qty = $this->input->post('qty');
$data = array();
for ($i = 0; $i <= $qty; $i++) {
$array = array(
'epin' => mt_rand(100000, 999999),
'amount' => $epin_amt,
);
array_merge($data, $array);
}
print_r($data) ; // Produce : array( )
You have to assign the merged array back to your $data variable:
<?php
$epin_amt = /*$this->input->post('amount')*/ 5;
$qty = /*$this->input->post('qty')*/6;
$data = array();
for ($i = 0; $i <= $qty; $i++) {
$array = array(
'epin' => mt_rand(100000, 999999),
'amount' => $epin_amt,
);
$data = array_merge($data, $array);
}
print_r($data) ;
array_merge returns array. You need something like this:
$result = array_merge($data, $array);
You are merging the arrays but it's not done by reference so you're throwing the resulting array away. array_push() it instead, that will keep adding the arrays to your $data array:
<?php
$epin_amt = 10;
$qty = 20;
$data = array();
for ($i = 0; $i <= $qty; $i++) {
$array = array(
'epin' => mt_rand(100000, 999999),
'amount' => $epin_amt,
);
array_push($data, $array);
}
print_r($data) ;

How can we find the Duplicate values in array using php?

I would like to know, how can we detect the duplicate entries in array...
Something like
$array = array("192.168.1.1", "192.168.2.1","192.168.3.1","192.168.4.1","192.168.2.1","192.168.2.1","192.168.10.1","192.168.2.1","192.168.11.1","192.168.1.4") ;
I want to get the number of Duplicity used in array (C class unique).
like this
192.168.1.1 = unique
192.168.2.1 = Duplicate
192.168.3.1 = unique
192.168.4.1 = unique
192.168.2.1 = Duplicate
192.168.2.1 = Duplicate
192.168.10.1 = unique
192.168.2.1 = Duplicate
192.168.11.1 = unique
192.168.1.4 = Duplicate (Modified)
I tried this code like this style
$array2 = array() ;
foreach($array as $list ){
$ips = $list;
$ip = explode(".",$ips);
$rawip = $ip[0].".".$ip[1].".".$ip[2] ;
array_push($array2,$rawip);
}
but i am unable to set the data in right manner and also unable to make the loop for matching the data.
modified values
Thanks
SAM
Try this : this will give you the count of each value
$array = array("192.168.1.1", "192.168.2.1","192.168.3.1","192.168.4.1","192.168.2.1","192.168.2.1","192.168.10.1","192.168.2.1","192.168.11.1") ;
$cnt_array = array_count_values($array)
echo "<pre>";
print_r($cnt_array);
$res = array();
foreach($cnt_array as $key=>$val){
if($val == 1){
$res[$key] = 'unique';
}
else{
$res[$key] = 'duplicate';
}
}
echo "<pre>";
print_r($res);
use array_unique($array) function.
it will give you below output.
Array
(
[0] => 192.168.1.1
[1] => 192.168.2.1
[2] => 192.168.3.1
[3] => 192.168.4.1
[6] => 192.168.10.1
[8] => 192.168.11.1
)
And total duplicate count must be :
array_count_values($array)
Try this, hope it'll work
$FinalArray=array();
$arrayLen=count($array);
for($i=0; $i<$arrayLen; $i++)
{
if(!in_array($array[$i],$FinalArray))
$FinalArray[]=$array[$i];
}
Now in $FinalArray you got all the unique ip
Try this:
for ($i = 0; $i < count($array); $i++)
for ($j = $i + 1; $j < count($array); $j++)
if ($array[$i] == $array[$j])
echo $array[$i];
use in_array() function to check value is or not in array
<?php
$output ='';
$array = array(0, 1, 1, 2, 2, 3, 3);
$isArraycheckedvalue = array();
for ($i=0; $i < sizeof($array); $i++)
{
$eachArrayValue = $array[$i];
if(! in_array($eachArrayValue, $isArraycheckedvalue))
{
$isArraycheckedvalue[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated no <br/>";
}
else
{
$isArraycheckedvalue[] = $eachArrayValue;
$output .= $eachArrayValue. " Repated yes <br/>";
}
}
echo $output;
?>
find the Duplicate values in array using php
function array_repeat($arr){
if(!is_array($arr))
return $arr;
$arr1 = array_unique($arr);
$arr3 = array_diff_key($arr,$arr1);
return array_unique($arr3);
}

PHP Array explode single value

I have an array with a single value collected from database.
Within a while loop I wish to explode this for every two values.
Example:
$data = array('20;40;60;80;100;150;200;300;500;1000');
I want to explode this value and end up with the following loop:
$lowprice = "20";
$highprice = "40";
I couldn't find any examples of this.
Many thanks everyone who answered!
You can use preg_match_all().
Example:
$text = '20;40;60;80;100;150;200;300;500;1000';
preg_match_all("/([^;]+);([^;]+)/", $text, $pairs, PREG_SET_ORDER);
foreach ($pairs as $pair) {
// ...
$lowvalue = $pair[1];
$highvalue = $pair[2];
// ...
}
If you really must use explode and a while loop, the following will also work:
$text = '20;40;60;80;100;150;200;300;500;1000';
$data = explode(';', $text);
$i = 0;
$count = count($data);
while ($i < $count) {
// ...
$lowvalue = $data[$i++];
$highvalue = $data[$i++];
// ...
}
If you just want the first and second values as your low/high:
$data = array('20;40;60;80;100;150;200;300;500;1000');
list($lowprice,$highprice) = explode(';',current($data));
echo '$lowprice=',$lowprice,PHP_EOL;
echo '$highprice=',$highprice,PHP_EOL;
If you want an array of lows and highs:
$data = array('20;40;60;80;100;150;200;300;500;1000');
$lowprices = $highprices = array();
$data = explode(';',current($data));
$dataCount = count($data);
var_dump($data);
for ($i=0; $i < $dataCount; $i += 2) {
$lowprices[] = $data[$i];
$highprices[] = $data[$i+1];
}
echo '$lowprices=';
var_dump($lowprices);
echo '$highprices=';
var_dump($highprices);
EDIT
Why not start out with a proper array of values in the first place: it would simplify this a lot
$data = array(20,40,60,80,100,150,200,300,500,1000);
list($lowprice,$highprice) = $data;
echo '$lowprice=',$lowprice,PHP_EOL;
echo '$highprice=',$highprice,PHP_EOL;
or
$data = array(20,40,60,80,100,150,200,300,500,1000);
$lowprices = $highprices = array();
$dataCount = count($data);
var_dump($data);
for ($i=0; $i < $dataCount; $i += 2) {
$lowprices[] = $data[$i];
$highprices[] = $data[$i+1];
}
echo '$lowprices=';
var_dump($lowprices);
echo '$highprices=';
var_dump($highprices);
Explode initially on the ;. Then in a for loop incrementing by 2, you can assign the current and next values to a sub-array:
$initarray = explode(";", "20;40;60;80;100;150;200;300;500;1000");
$num = count($initarray);
// Main array to hold subarrays
$outputarray = array();
for ($i=0; $i<$num; $i=$i+2) {
// Add the current pair ($i and $i+1) to a sub-array
$outputarray[] = array("lowprice"=>$initarray[$i], "highprice"=>$initarray[$i+1]);
}
Outputs:
Array
(
[0] => Array
(
[lowprice] => 20
[highprice] => 40
)
[1] => Array
(
[lowprice] => 60
[highprice] => 80
)
[2] => Array
(
[lowprice] => 100
[highprice] => 150
)
[3] => Array
(
[lowprice] => 200
[highprice] => 300
)
[4] => Array
(
[lowprice] => 500
[highprice] => 1000
)
)
You may use loop like this one (using explode() and array_shift()):
$data = explode( ';', '20;40;60;80;100;150;200;300;500;1000');
while( count( $data) > 1){
$lowprice = array_shift( $data);
$highprice = array_shift( $data);
}
Or use for loop (should be more effective than calling count() in every iteration):
$count = count( $data);
for( $i = 0; $i < $count; $i+=2){}

How to insert a single character between each element in a string to have an array of options

Using PHP, let's say I have this string:
$letters = "abcde";
I would like to add the character "7" between every character, but so it only occurs once. The result should be an array as follows:
$lettersArray = array(
7abcde,
a7bcde,
ab7cde,
abc7de,
abcd7e,
abcde7
);
Note: the length of $letters is dynamic from 1 to 12 characters
I have tried using loops with array_splice and str_split with implode, but I can't quite figure out the right logic.
It is very simple , do like this
echo implode("+", str_split('vimal')); // OUTPUT : v+i+m+a+l
Have a nice day
Try this:
$letters ='abcdefghi';
$lettersArray = array();
for($i=0;$i < strlen($letters)+1; $i++) {
$new = substr($letters, 0, $i);
$new .= '7';
$new .= substr($letters, $i);
$lettersArray[] = $new;
}
print_r($lettersArray);
What this does is take each element of the array, and inserts the letter 7 in an incrementing fashion into the array item.
$split_letters = str_split($letters);
$letters_array = array();
for($i = 0; $i <= count($split_letters); $i++) {
$start_letters = array_slice($split_letters, 0, $i);
$end_letters = array_slice($split_letters, $i);
$letters_array[] = array_merge($start_letters, array(7), $end_letters);
}
After 2 hours (including writing this question) I finally also came up with a solution that is similar to the others posted here. It's posted below, but I prefer other solutions posted here.
$letters = "abcde";
$results = array();
$lettersArray = str_split($letters);
foreach ($lettersArray as $key => $lets) {
$tempArray = $lettersArray;
array_splice($tempArray, $key, 0, "7");
$results[] = implode($tempArray);
}
$results[] = $letters . "7"; //required for the final combination
print_r($results);
Try this
$letters = "abcde";
$character = "7";
$len = strlen($letters);
$lettersArray = array();
for($i=0; $i <= $len; $i++)
{
$temp = "";
$temp = substr($letters, 0, $i) . $character . substr($letters, $i);
$lettersArray[] = $temp;
}
http://codepad.viper-7.com/gFByJb

Categories