0

Say, I've got the following code in PHP:
included_file.php:

DEFINE("MSWFFN",serialize(array(
  "mnu"=>array("n"=>"topmnu.swf","w"=>"980px","h"=>"80px","i"=>"mnu","p"=>"&subp=home")
)));

main_file.php:

require_once("included_file.php");
global $MSWFFN;
$MSWFFN=unserialize(MSWFFN);
$swf=array_slice($MSWFFN,0,1,false); //first swf from cfg
var_dump($MSWFFN);
var_dump($swf);

Based on what's said [in this question][1] and on the [php website][2] it should return an array with integer keys, but it does not.
Any idea on why does it not change the 'mnu' key to 0?
Output:

array (size=1)
  'mnu' => 
    array (size=5)
      'n' => string 'topmnu.swf' (length=10)
      'w' => string '980px' (length=5)
      'h' => string '80px' (length=4)
      'i' => string 'mnu' (length=3)
      'p' => string '&subp=home' (length=10)

array (size=1)
  'mnu' => 
    array (size=5)
      'n' => string 'topmnu.swf' (length=10)
      'w' => string '980px' (length=5)
      'h' => string '80px' (length=4)
      'i' => string 'mnu' (length=3)
      'p' => string '&subp=home' (length=10)

Oh, btw my Apache Version is Apache/2.2.23 (Win32) PHP/5.3.18 (VertrigoServ v2.29) [1]: PHP: Get n-th item of an associative array [2]: https://www.php.net/manual/en/function.array-slice.php

2 Answers 2

2

You are not using numeric keys.

Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

There's even a 10-year-old comment regarding this "surprise".

Also, for what it's worth, your output of the original variable and the output of array_slice() is exactly the same, making the latter a bit useless.

Sign up to request clarification or add additional context in comments.

2 Comments

oh, guess i misunderstood that it turns the keys into numeric ones whereas it just returns the Nth element. Thank you very much!
It will modify and revert numeric keys, but it will re-match and preserve string keys. Note that numeric keys includes ones defined as strings, such as array("12" => "Something..."). Play around with it.
1

To accomplish that, you can use array_values():

var_dump(array_values($MSWFFN));

Output:

Array (
    [0] => Array
        (
            [n] => topmnu.swf
            [w] => 980px
            [h] => 80px
            [i] => mnu
            [p] => &subp=home
        )

    )

1 Comment

exactly what i wanted to accomplish! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.