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){}
Related
I have been asked a question in an interview to sort a string by length of its words in php without using built in functions.No idea how to do this. Can somebody help me with this?
String: Sort a string by length of its words
Thanks in advance
$array = array('harish', 'mohan', 'jaideep', 'hari');
for ($i = 1; $i < count($array); $i++) {
for ($j = $i; $j > 0; $j--) {
if (strlen($array[$j]) < strlen($array[$j - 1])) {
$tmp = $array[$j];
$array[$j] = $array[$j - 1];
$array[$j - 1] = $tmp;
}
}
}
var_dump($array);
you could try this:
$string = "this is my test string";
$array = explode(" ", $string);
$result = array();
foreach ($array as $key => $string){
$counter = 0;
for($i = 0;;$i++){
if (!isset($string[$i])){
break;
}
$counter++;
}
$result[$counter][] = $string;
}
This splits your string and puts it into an array, where the keys are the counted characters. The problem now is, that you need to sort the array by the keys, which can be acquired by using ksort.
I do not know if you may use it, if not, refer to this answer (use of sort) or this answer (no sort), this should do the trick (though I didn't test it).
This is the solution that I propose. I added some comments.
<?php
/* First part split the string in their words and store them in an array called $words.
* The key is the length of the word and the value is an array with all the words having the same length as the key.
* e.g
* Array
(
[4] => Array( [0] => Sort )
[1] => Array( [0] => a )
[6] => Array( [0] => string, [1] => length)
[2] => Array( [0] => by, [1] => of)
[3] => Array( [0] => its )
)
*/
$str = "Sort a string by length of its words";
$word = '';
$i = 0;
$word_length = 0;
$words = [];
$max = -1;
while( isset($str[$i]) ) {
if( $str[$i] !== ' ' ){
$word .= $str[$i];
$word_length++;
}else{
//This is going to save the size of the longhest word in the array:
$max = ($word_length > $max) ? $word_length : $max;
//store the
$words[$word_length][] = $word;
$word = '';
$word_length = 0;
}
$i++;
}
//print_r($words); // uncomment this if you wanna see content of the array.
//The if-condition is for ascending order or descending order.
$order = "DESC"; // "ASC" | "DESC"
$res = '';
if( $order === "DESC") {
for( $i = $max; $i>=0 ; $i--) {
if( ! isset($words[$i]) ) { continue; }
foreach($words[$i] as $word){
$res .= $word . ' ';
}
}
}else {
//ascending order:
for( $i = 0; $i<=$max; $i++) {
if( ! isset($words[$i]) ) { continue; }
foreach($words[$i] as $word){
$res .= $word . ' ';
}
}
}
echo $res . "\n";
?>
Is this what you want?
Note: isset, echo, print, etc are PHP language constructs whereas print_r(), strlen(), etc. are built in functions. If you have doubts, you can see what's the difference in this post. What is the difference between a language construct and a "built-in" function in 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];
im trying to convert a comma separated into a multidimensional array to create a menu structure of this.
this is what i have already..
for ($i=0; $i < $count; $i++) {
if($i > 0){
array_push($tagmenu[0][$pretags[$i-1]], array($pretags[$i]=>array()));
} else {
array_push($tagmenu, array($pretags[$i]=>array()));
}
}
i have this as a string
$tags = 'image,landscape,night';
and i want it to look like this
Array(
[images] = Array (
[landscape] = Array(
[night] = Array ()
)
)
i'm searching my fingers off on this
$tags = 'image,landscape,night';
$newArray = array();
$wrkArray = &$newArray;
foreach(explode(',',$tags) as $tag) {
$wrkArray[$tag] = array();
$wrkArray = &$wrkArray[$tag];
}
unset($wrkArray);
var_dump($newArray);
I've got an array of 'contestant entrants' which can be shown like this:
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
...
)
From these entries I need to create another array called $draw.
The $draw array will have username repeated as many times as it's corresponding number_of_entries. So for the above example it might look like this:
$draw = array("122", "123", "123", "123", "123", "124", "124", "124")
I want this so that I can later generate a random number, and find the winner by doing something like $draw[$randomNumber];
However I cannot get my head around how to create that $draw array from the $all_entrants array... Any help will be greatly appreciated!
I assume you're looking for something like this?
$draw = array();
foreach($all_entrants as $entrant) // loop through array with entrants
for ($i = 0; $i<$entrant['number_of_entries']; $i++) //get number of entries
$draw[] = $entrant['username']; //add them to the $draw array
I think it's a question about select one from a group of name which has different weight.
maybe an array like this
$group = array(
array('122' => 1),
array('123'=> 4),
array('124'=> 3)
);
First Calculate the sum of the weight, or may be it has been known already
$total_weight = 0;
foreach($group as $weight){
$total_weight += $weight;
}
Then generate a random number from 0 to $total_weight, eg. 0<=$rand_number
$current_total = 0;
foreach($group as $name => $weight){
if($rand_number <= $current_total)
return $name;
$current_total += $weight;
}
--
BTW, I'm new here, more to learn:)
<?php
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}
$draw = array();
foreach($all_entrants as $entrant) {
for($i=0; $i<$entrant['number_of_entries']; $i++) {
$draw[] = $entrant['username'];
}
}
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3),
);
$draw = array();
foreach($all_entrants as $entrant) {
$draw = array_merge(
$draw,
array_fill(0, $entrant['number_of_entries'], $entrant['username'])
);
}
var_dump($draw);
Try this
$newarray=array();
foreach($all_entrants as $list){
for($i=1;$i<=$list['number_of_entries'];$i++){
array_push($newarray,$list['username']);
}
}
<?php
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
$draw = array();
for ($i = 0; $i < count($all_entrants); $i++)
{
$entrants = $all_entrants[$i];
$name = $entrants["username"];
$entry_count = $entrants["number_of_entries"];
for ($j = 0; $j < $entry_count; $j++) $draw[] = $name;
}
print_r($draw);
?>
Hope it helps.
check this :--
$result=array();
$all_entrants = array(
array('username'=>'122', 'number_of_entries'=>1),
array('username'=>'123', 'number_of_entries'=>4),
array('username'=>'124', 'number_of_entries'=>3)
);
foreach($all_entrants as $value)
for($i=0;$i<$value['number_of_entries'];$i++)
array_push($result,$value['username']);
echo '<pre>';
print_r($result);
output :-
Array
(
[0] => 122
[1] => 123
[2] => 123
[3] => 123
[4] => 123
[5] => 124
[6] => 124
[7] => 124
)
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);
}