adding previous array values to newer array values - php

$test = 'test1/test2/test3/test4';
I am trying to get a array from that $test above which i'd like to output like below.
Array
(
[0] => /
[1] => /test1/
[2] => /test1/test2/
[3] => /test1/test2/test3/
[4] => /test1/test2/test3/test4/
)
I've tried loops but can't quite figure out how to get it quite right.

Try to make loop like :
$test = 'test1/test2/test3/test4';
$test_arr = explode("/", $test);
$test_size = count($test_arr);
$count = 1;
$new_test_arr = array('/');
for ($i=0; $i<$test_size; $i++)
{
$new_test_arr[$count] = $new_test_arr[$i] . $test_arr[$i] . "/"
$count++;
}

Here's a way to do it very compactly:
$parts = explode("/", $test);
for($i = 0; $i <= count($parts); ++$i) {
echo "/".implode("/", array_slice($parts, 0, $i))."\n";
}
Not terribly efficient, but I don't think efficiency would matter in something trivial you 'd only do once. On the plus side, the loop modifies no variables which makes it easier to reason about.
See it in action.

A very easy and simple way, for this case would be
$test = 'test1/test2/test3/test4';
$arr = explode("/", $test);
$t = "";
$newArray = array("/");
foreach($arr as $value) {
$t .= "/".$value;
$newArray[] = $t;
}
print_r($newArray);
Demo

Related

create array with key and value from string

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];

PHP Array compare using loops

I am using this piece of code to compare two php arrays, I got all matched items rightly but unfortunately i am not succeeding in getting non matched items. Here is my code.
<?php
$filter1 = "blueberries,abc,cornstarch,sugar";
$cval = strtoupper($filter1);
$parts1 = explode(',',$cval);
$filter2 = "water,blueberries,sugar,cornstarch";
$values = strtoupper($filter2);
$parts2 = explode(',', $values);
$m=0;
$nm=0;
for($i = 0; $i< count($parts1); $i++)
{
for($j = 0; $j< count($parts2); $j++)
{
if($parts1[$i] == $parts2[$j])
{
$m++;
$p[] = $parts1[$i];
}
else{
$nm++;
$q[] = $parts1[$i];
}
}
}
echo $m;
echo "<br />";
echo $nm;
echo "<br />";
print_r($p);
echo "<br />";
print_r($q);
?>
Can someone help me sorting out this problem, As i dont want to use builtin array comparison functions.
I would use the internal functions for this (if I understood your question)
Matched:
$matched = array_intersect($parts1, $parts2);
Difference:
$difference = array_diff($parts1, $parts2);
Or in your world of for loops:
<?php
$filter1 = "blueberries,abc,cornstarch,sugar";
$cval = strtoupper($filter1);
$parts1 = explode(',', $cval);
$filter2 = "water,blueberries,sugar,cornstarch";
$values = strtoupper($filter2);
$parts2 = explode(',', $values);
$matched = $not_matched = array();
for ($i = 0; $i < count($parts1); $i++)
{
if (in_array($parts1[$i], $parts2))
{
$matched[] = $parts1[$i];
}
else
{
$not_matched[] = $parts1[$i];
}
}
print_r($matched);
print_r($not_matched);
?>
I have been working on adding another loop instead of using in_array() but I'm not going to update my answer for two reasons.
1) Use
$matched = array_intersect($parts1, $parts2);
$difference = array_diff($parts1, $parts2);
Writing this much code instead of two lines is against my religion.
2) The only reason to create this amount of code stricly not using array_* or in_array functions must be for some quiz or test, which I want to enter and win.
Use array_intersect, array_diff and array_merge
$filter1 = "blueberries,abc,cornstarch,sugar";
$cval = strtoupper($filter1);
$parts1 = explode(',',$cval);
$filter2 = "water,blueberries,sugar,cornstarch";
$values = strtoupper($filter2);
$parts2 = explode(',', $values);
print_r(array_intersect($parts1, $parts2));
print_r(array_merge(array_diff($parts1, $parts2), array_diff($parts2, $parts1)));
Array ( [0] => BLUEBERRIES [2] => CORNSTARCH [3] => SUGAR ) Array ( [0] => ABC [1] => WATER )
You are doing the cartesian product of the two arrays.
If you find that $parts1[$i] == $parts2[$j], it is correct to add $parts1[$i] to $p, but the opposite assumption (if they are different then add to $q) is wrong.
You should start with all elements in $q and when you have a match, add it to $p and remove it from $q.
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);
?>
This is the php library function.

PHP Extract Values From One String Based on a Pattern Defined in Another

I have two strings:
$first = '/this/is/a/string';
$second = '/this/:param1/a/:param2';
And I'm trying to get this:
$params = array('param1' => 'is', 'param2' => 'string');
But getting from point a to b is proving more than my tired brain can handle at the moment.
Anything starting with a ':' in the second string defines a variable name/position. There can be any number of variables in $second which need to be extracted from $first. Segments are separated by a '/'.
For fun I'll throw in a slightly different approach. It takes about half the time as cletus's (whose answer is excellent) because it uses less regex and conditionals:
$first = '/this/is/a/string';
$second = '/this/:param1/a/:param2';
$firstParts = explode('/', $first);
$paramKeys = preg_grep('/^:.+/', explode('/', $second));
$params = array();
foreach ($paramKeys as $key => $val) {
$params[substr($val, 1)] = $firstParts[$key];
}
/*
output:
Array
(
[param1] => is
[param2] => string
)
*/
Input:
$first = '/this/is/a/string';
$second = '/this/:param1/a/:param2';
$src = explode('/', $first);
$req = explode('/', $second);
$params = array();
for ($i = 0; $i < count($req); $i++) {
if (preg_match('!:(\w+)!', $req[$i], $matches)) {
$params[$matches[1]] = $i < count($src) ? $src[$i] : null;
}
}
print_r($params);
Output:
Array
(
[param1] => is
[param2] => string
)

Generating word stacks from arrays

I'm trying to do a simple word cloud exercise in PHP but with little twist. I have everything else done but I can't figure out how to do a loop that combines the words.
Here's example that will make it little bit easier to understand what I'm trying to do:
I have array like this:
$arr = array('linebreak','indent','code','question','prefer','we','programming')
Now I'm trying to do a function that starts going thru that array and gives me arrays like these:
Array(
[0] => 'linebreak'
[1] => 'linebreak indent'
[2] => 'linebreak indent code'
)
Array(
[0] => 'indent'
[1] => 'indent code'
[2] => 'indent code question'
)
So basically it goes thru the original words array word by word and makes these little arrays that has 1 to 5 next words combined.
$arr = array('linebreak','indent','code','question','prefer','we','programming');
$val = '';
foreach($arr as $key=>$value)
{
$val .= ' '.$value;
$newArr[] = $val;
}
print_r($newArr);
$a = array('linebreak','indent','code','question','prefer','we','programming');
for($i = 0; $i < count($a); $i++) {
$p = array();
for($k = $i; $k < count($a); $k++) {
$p[] = $a[$k];
$r[] = implode(' ', $p);
}
}
print_r($r);
Recursion may be the way to go. I haven't exhaustively checked the below for syntax.
function descend($arr, $offset=0) {
global $holder;
$tmp=array_slice($arr,$offset,5); //limits the result set for each starter word to 5 or fewer children
foreach($tmp as $word) {
$val .= ' '.$word;
$holder[$offset][]=$val;
}
$offset++;
if($offset<count($arr)) descend($arr,$offset);
}
$arr = array('linebreak','indent','code','question','prefer','we','programming');
$holder = descend($arr);

What is the built-in PHP function for "compressing" or "defragmenting" an array?

I know it'd be trivial to code myself, but in the interest of not having more code to maintain if it's built in to PHP already, is there a built-in function for "compressing" a PHP array? In other words, let's say I create an array thus:
$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;
What I want is an array where $array[0] == 5, $array[1] == 7, $array[2] == 9.
I could do this:
function array_defragment($array) {
$squashed_array = array();
foreach ($array as $item) {
$squashed_array[] = $item;
}
return $squashed_array;
}
...but it seems like the kind of thing that would be built in to PHP - I just can't find it in the docs.
Just use array_values:
$array = array();
$array[2000] = 5;
$array[3000] = 7;
$array[3500] = 9;
$array = array_values($array);
var_dump($array === array(5, 7, 9));
A newer method is the spread operator ...
$arr = ['red', 'orange', 'yellow', 'green'];
unset($arr[2]);
$arr = [...$arr];
print_r($arr);
Gives me a result:
Array
(
[0] => red
[1] => orange
[2] => green
)
However, do keep in mind, the spread operator ... is significantly slower as a proportion in comparison to array_values. You may run the following test:
<?php
function getTimeNow()
{
return microtime(true) * 1000;
}
$arr1 = [];
for ($i = 0; $i < 100000; $i++) {
$arr1[$i + rand(0,4)] = $i;
}
$start = getTimeNow();
$spreadTest = [...$arr1];
echo "\nTime taken for spread: " . getTimeNow() - $start;
$start = getTimeNow();
$arrayValues = array_values($arr1);
echo "\nTime taken for array_values: " . getTimeNow() - $start;
Results are:
$ php index.php
Time taken for spread: 0.8779296875
Time taken for array_values: 0.4228515625

Categories