Reputation: 481
I have an associative array like this
$imagePaths = array(
'logo' => "logo.jpg",
'facebook-logo' => "facebook-icon.jpg",
'twitter-logo' => "twitter-icon.jpg",
'linkedin' => "linkedIn.jpg"
);
for me to call logo, I use below code
$ClassInstance->imagePaths['logo'];
But I would also like to be able to call it using
$ClassInstance->imagePaths[0];
Is there anyway to do this?
Upvotes: 0
Views: 72
Reputation: 155
You could store a second array using array_values()
:
$imagePathsKeyed = array_values($imagePaths);
EDIT: I've expanded the example code to help here
<?php
class SomeObject
{
public $imagePaths;
public $keyedImagePaths;
public function __construct()
{
$this->imagePaths = array(
'logo' => "logo.jpg",
'facebook-logo' => "facebook-icon.jpg",
'twitter-logo' => "twitter-icon.jpg",
'linkedin' => "linkedIn.jpg"
);
$this->keyedImagePaths = array_values($this->imagePaths);
}
}
$classInstance = new SomeObject();
// logo.jpg
echo $classInstance->imagePaths['logo'];
// logo.jpg
echo $classInstance->keyedImagePaths[0];
Upvotes: 4
Reputation: 76636
You can achieve this with array_keys()
:
$keys = array_keys($imagePaths);
$ClassInstance->imagePaths[$keys[0]];
Upvotes: 6