1

Ok so I have been struggling with this for hours now and I cannot seem to figure out what I'm trying to do. I have an array with many percent values placed inside and I'm printing out the first 5 of them. The $percent variables are acquired through similar_text

$array=array($percent12, $percent13, $percent14,
    $percent15, $percent16, $percent17,
    $percent18, $percent19, $percent110,
    $percent111, $percent112, $percent113,
    $percent114, $percent115, $percent116,
    $percent117, $percent118, $percent119,
    $percent120);

print_r(array_slice($array,0,5));

and it outputs like this:

Array ( [0] => 36.015505697169 [1] => 2.4181626187962 [2] => 2.4181626187962 [3] => 5.2153134902083 [4] => 100 )

So what i'm trying to figure out here is if it's possible to print the results of my array as they are listed above. example output would look like this:

Array ( [percent12] => 36.015505697169 [percent13] => 2.4181626187962 [percent14] => 2.4181626187962 [percent15] => 5.2153134902083 [percent16] => 100 )

i feel like this isn't possible, but if not, is there a way to assign the

[0]=> 36.015505697169 [1]=> 2.4181626187962 

...etc to output something else say like:

[web0]=> 36.015505697169 [web1] => 2.4181626187962

Please help!! It's driving me crazy!!

3 Answers 3

1

You need to make it an associative array:

$array=array('percent12' => $percent12, 
             'percent13' => $percent13,
             ...);
Sign up to request clarification or add additional context in comments.

3 Comments

This was exactly what I was looking for thank you so much! I tried this approach before but couldn't get it to work for some reason, but I got it working now! Thank you so much it's greatly appreacited!!
Maybe something you can also help me out with.. as soon as I used an r_sort on my array it went back to how it was acting before. Any idea why this might be happening?
Use arsort to sort an associative array and keep the key associations.
1

I recommend using array_combine()

Basically you're just going to setup your new array with the keys, and pass in your current array for the values, thus creating a new array with the keys you want in the right place.

3 Comments

Once you're done, just unset the arrays you don't need and free up a little memory ;)
This worked great for me thanks! I was actually looking for more of the approach with the associative arrays, but this worked great too thank you so much!!!!
array_combine is just another way to create an associative array.
0

Try like

$myArr = array_slice($array,0,5);
$i = 0;
foreach($myArr as $key => $value) {
   $newArr['web'.$i++] = $value;
}
print_r($newArr);

Comments

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.