0

I have an array

print_r($myarray); Array ( [0] => text one ) Array ( [0] => text two ) Array ( [0] => text three ) ... 

When I use slice

print_r(array_slice($myarray,1,2)); Array ( ) Array ( ) Array ( ) Array ( ) ...... 

I get an empty array, how can I slice this array in half?

0

1 Answer 1

1

You actually have an array that contains arrays which probably might be what is causing the issue for you. Though I do not see how you get the result you posted... It mighty be that you actually apply the slice function to each element of the output array. Then certainly you will get an empty array for each iteration. As to be expected, since each element you iterate over contains only a single element. So slicing from position 1 will result in an empty array each time...

Consider this simple example using a plain array:

<?php $input = ["one", "two", "three", "four", "five", "six"]; $output = array_slice($input, 1, 2); print_r($output); 

The output is:

Array ( [0] => two [1] => three ) 

So php's array_slice() function works just as expected...


Same with an array of arrays as you suggest in your post:

<?php $input = [["one"], ["two"], ["three"], ["four"], ["five"], ["six"]]; $output = array_slice($input, 1, 2); print_r($output); 

The output of that is, as expected:

Array ( [0] => Array ( [0] => two ) [1] => Array ( [0] => three ) ) 

Also considering your second comment below, that you have some words in a single string (which mighty be what you describe) I get a meaningful result myself:

<?php $input = explode(' ', "one two three four five six"); $output = array_slice($input, 1, 2); print_r($output); 

The output, as expected, is:

Array ( [0] => two [1] => three ) 
Sign up to request clarification or add additional context in comments.

10 Comments

I convert string to array like this: ` $myarray = $product["model_number"]; ` ` $myarray= explode(', ', $myarray); ` How can i changed the array index? Thanks
@Edo I cannot answer to that since I don't know the structure of $product["model_number"].
When i do print_r($product["model_number"]); I get: one two three four Strings in one line together
@Edo I added a third variant to demonstrate that slicing is not your issue. You really need to find out what data structure you actually have. Why do you explode by ', ' if you claim to have a string separated by only whitespaces?
The output of $product["model_number"] in face it like this: number onenumber twonumber three i have a string from 2/3 words, the last word of the first and the first of the next string is connected. How to covert this string to array correctly?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.