Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of value from an array in php

I have the below php array $tempStyleArray which is created by spiting a string.

$tempStyleArray = preg_split( "/[:;]+/", "width: 569px; height: 26.456692913px; margin: 0px; border: 2px solid black;" );


Array
(
    [0] => width
    [1] =>  569px
    [2] =>  height
    [3] =>  26.456692913px
    [4] =>  margin
    [5] =>  0px
    [6] =>  border
    [7] =>  2px solid black
    [8] => 
)

I have to get index/key of the element height from this array. I tried below codes but nothing seems to be working for me.

foreach($tempStyleArray as  $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     $key = $i;
   }
} 

in above solution it not satisfying the condition ever :(

$key = array_search('height', $tempStyleArray); // this one not returning anything

Help me to solve this? Is there any problem with my array format?

like image 724
chriz Avatar asked Dec 19 '22 04:12

chriz


1 Answers

foreach($tempStyleArray as  $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     $key = $i;
   }
} 

and what is $i?, better use key=>value for.

foreach($tempStyleArray as  $key => $value)
{
   if($value == "height") // not satisfying this condition
   {
     echo $value;
     echo '</br>';
     echo $key;
   }
} 

Looking at your array, it appears that you want to say that "width" will be 569px, then maybe is better to do this:

$tempStyleArray = array(
    "width" =>  "569px",
    "height" => "26.456692913px",
    "margin" => "0px",
    "border" => "2px solid black"
);

That way you can just say

echo $tempStyleArray["width"];

This will be faster and you don't have to due with searching.

UPDATE:

for( $i == 1; $i < count($tempStyleArray); $i = $i+2)
{
    $newArray[ $tempStyleArray[$i-1] ] = $tempStyleArray[$i]
}

with that you can get an hash based array.

like image 151
lcjury Avatar answered Jan 12 '23 17:01

lcjury