John Magnolia
John Magnolia

Reputation: 16793

PHP check if array and to use only the last item from this array

The following method below works perfectly if $output is a string. Although in a rare case $output can be passed as an array.

How can I check if $output is an array and to only get the last part of the array.

/**
 * Output writer.
 *
 * @param string $output
 * @param Controller $oController
 * @throws Output_Exception
 */
public static function factory($output,Controller $oController) {       

    $outtype =  ucfirst(strtolower(str_replace(".","_",$output)));
    $classname = __CLASS__ . "_" . $outtype;

    try {

        Zend_Loader::loadClass($classname);
        $oOutputter = new $classname($oController);

        if(! $oOutputter instanceof Output_Abstract )
            throw new Output_Exception("class $classname is not an instance of Output_Abstract");

    } catch (Zend_Exception $e) {               
        throw $e;
    }

    return $oOutputter;
}

Errors:

Warning: strtolower() expects parameter 1 to be string, array given in C:\wamp\www\cms\webapp\library\Output.php on line 16

Warning: include_once(Output.php) [function.include-once]: failed to open stream: No such file or directory in C:\wamp\php\includes\Zend\Loader.php on line 146

var_dump($output)

array(2) { [0]=> string(6) "xml" [1]=> string(6) "smarty" } 

Upvotes: 1

Views: 766

Answers (3)

itsananderson
itsananderson

Reputation: 793

You should be able to use PHP's is_array() function. Something like the following should do it.

<?php
//...
$output = is_array($output) ? $output[count($output)-1] : $output;
//...
?>

This snippet will check if $output is an array, and if it is, it'll set $output to to the last element in the array. Otherwise, it will leave it unchanged.

You can read more about is_array() at the following link:

http://www.php.net/manual/en/function.is-array.php

EDIT: Looks like someone beat me to an answer, but I would recommend against using the end() function here. Doing so could have unexpected results if the code calling your function expects the array to be unmodified.

Upvotes: 1

Robik
Robik

Reputation: 6127

Try changing this:

$outtype =  ucfirst(strtolower(str_replace(".","_",$output)));

to this:

if(is_array($output))
    $outout= $output[count($outout)-1];
$outtype =  ucfirst(strtolower(str_replace(".","_",$output)));

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

if ( is_array($output) ) {
   $output= end($output);
}

see
http://docs.php.net/is_array
http://docs.php.net/function.end

Upvotes: 4

Related Questions