Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP match data into array

Tags:

php

I'm not sure if there is some kind of php function that will help me do this fairly simply or not. I figured I'd ask.

Let's say I have 5 products [prod1, prod2, prod3, prod4, prod5]

All of these products are related to eachother, so I need to arrive at something like this:

prod1, prod2, prod3, prod4, prod5

prod2, prod3, prod4, prod5, prod1

prod3, prod4, prod5, prod1, prod2

prod4, prod5, prod1, prod2, prod3

prod5, prod1, prod2, prod3, prod4

echo, save as variables, it doesn't matter to me.

In my example I said 5, but in reality there could be any number of products. Is there a function that does this automatically up to n products?? I don't even know what to really call this other then I'm matching them together.

like image 649
thindery Avatar asked Aug 01 '13 21:08

thindery


People also ask

How do you match data in an array?

iterate for-in loop over the array elements. Each iteration, matches first array elements to second array elements using indexOf() method, if they match then push elements into arr array. Sort arr array elements in ascending order and as well as return sorted array list.

How do you check if a value exists in an array in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How do you find a specific value in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


1 Answers

You can do this:

$arr = array($prod1, $prod2, $prod3, $prod4, $prod5);

for ($i = 0; $i < count($arr); $i++) {
    array_push($arr, array_shift($arr));
    print_r($arr);
}
like image 71
jh314 Avatar answered Sep 30 '22 15:09

jh314