Mayboy Mayboy - 1 year ago 34
PHP Question

How to avoid the previous values in php array overridden by the later ones?

How to avoid

34 overridden by 124
in the following
PHP
code? I just want to keep the
34
and
124
both.

$arr = array(12, 34, "df"=>43, "1"=>124, 65);
$num = count($arr);
reset($arr);
for ($i = 1; $i <= $num; ++$i) {
echo 'The Current Position:' . key($arr);
echo '<br />';
echo 'The Current Value:'. current($arr);
next($arr);
echo '<br />';
echo '<br />';
}

Answer

PHP will always treat all numeric keys as integers even if they are inside string variables or quotes.

The following can make it quite apparent:

<?php

$arr = [1 => 'hi', '2' => 'bye', 'a1' => 'hiha'];

var_export($arr);

The solution is to prefix the values that you don't want indexed as integers with a letter.

Note that mixing indexed and associative arrays indicates a serious lack of organization that you will regret later, if you don't already.