Reputation: 1165
This is my original array:
Array ( [0] => pid [1] => pname [2] => paddress [3] => pphone)
After using array_flip
, it becomes this, which is how I want it:
Array ( [pid] => 0 [pname] => 1 [paddress] => 2 [pphone] => 3)
However, I can't seem to use the array anymore. When I try to loop through each item, I get undefined offset.
Upvotes: 2
Views: 191
Reputation: 2166
if you were using a for loop before you flipped the array it will no longer work because the array becomes an associative array. You can use a foreach($array as $k => $v )
loop and it should work.
for loops only work with an array that is indexed numerically.
for($i=0;$i<count($array);$i++)
{
echo $array[$i];
}
foreach is used for associative arrays.
foreach($array as $k => $v)
{
echo $k.'=>'.$v;
}
Edit: you can use a foreach array with a numerically indexed array as well.
Upvotes: 1
Reputation: 1516
Sure, if you are trying to access it by a string-key then it will throw the error 'undefined offset x'.
You need to ensure that if you are running it through a loop then you need to specify the key and value:
foreach($array as $key => $value){
// do stuff
}
Or if you prefer you can get the values/keys without doing a loop, which is probably more efficient way of doing it:
$keys = array_keys($array);
$values = array_values($array);
$x = array_flip($array);
$flipped_keys = array_keys($x);
$flipped_values = array_values($x);
echo $x[$flipped_keys[0]];
Hopefully this will help
Upvotes: 0
Reputation: 3338
use foreach to loop the array
foreach($array as $key => $value){
echo "key=$key"."</br>";
echo "value=$value";
}
Upvotes: 0